BrennanHatton.com Posted November 15, 2015 Share Posted November 15, 2015 I want to create a dynamic interfaces for items in an inventory. I need the items to be button to view that item. And want that button to calla function with the item id as an argument. inventory[index].button = game.add.button(inventory[index].x - (1030/2), inventory[index].y, 'equipmentButton', this.EquipItem, this); ... EquipItem: function(index) { }; adamsko 1 Link to comment Share on other sites More sharing options...
Zarko Kaktus Posted November 16, 2015 Share Posted November 16, 2015 Hi, and welcome to Phaser wold To make it more clear:I will assume that you create your buttons in loop, "for" loop - for example..your problem is how to provide "index" value in function event callback "EquipItem"inventory array/object with "index" as a key is already an existing object"EquipItem" is function part of "this" object and buttons are created in function also part of "this" object Here you are, a three possible solutions: 1. Using Phaser "onInputDown" Signal event https://github.com/photonstorm/phaser/blob/v2.4.4/src/gameobjects/Button.js#L158inventory[index].button = game.add.button(inventory[index].x - (1030/2), inventory[index].y, 'equipmentButton');inventory[index].button.onInputDown.add(this.EquipItem, this, 0 /* priority */, index);// But you will need to adjust your function like thisEquipItem: function (btnObj /* reference to button */, ev /* event object */, index /* your index provided value */) { console.log("index: ", index);},2. Using "bind" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bindinventory[index].button = game.add.button(inventory[index].x - (1030/2), inventory[index].y, 'equipmentButton', this.EquipItem.bind(this, index), this);3. You can use closureinventory[index].button = game.add.button(inventory[index].x - (1030/2), inventory[index].y, 'equipmentButton', (function (_this, index) { return function () { _this.EquipItem.call(_this, index); }})(this, k));Hope this will help you! adamsko 1 Link to comment Share on other sites More sharing options...
BrennanHatton.com Posted November 17, 2015 Author Share Posted November 17, 2015 Hey Zarko, Thank you!!! That is just what I need. Link to comment Share on other sites More sharing options...
Recommended Posts