Jump to content

Passing custom data to "on" function


Tahatan
 Share

Recommended Posts

I have an array of objects, each object includes a sprite and a bunch of extra data (position data, flags etc). I give each object an "on" mousedown function on the sprite like so:

 

selectableContainers.push(createSprite(data).sprite.on('mousedown', onPressed));

//createSprite returns an object with a sprite and the other data

 

When the sprite is pressed I need to move it using the data in the object but of course in the onPressed function I only have access to the sprite, not the object that contains the sprite and therefore I do not have the positional data to use.

 

Is there anyway to either get that data into the onPressed function or perhaps a way for me to know which object in my selectableContainers array this event has triggered on?

 

ala:

onPressed()

{

this.position = objectData.newPosition; //get the objectData for this sprite into this function?

 

or

 

this.position = selectableContainers[ thisObjectsId ].newPosition; //find thisObjectsId from this sprite?

}

 

I am struggling to find a way around this but it seems like there should be something quite straightforward that allows me to do what I want that I have perhaps missed?

 

Any help is greatly appreciated.

 

Thanks.

Link to comment
Share on other sites

Have you tried using Function.prototype.bind?
 

var spriteData = createSprite(data);selectableContainers.push(spriteData.sprite.on('mousedown', onPressed.bind(spriteData));//  ...function onPressed() {    // `this` is now the sprite data object    console.log(this.sprite);    console.log(this.newPosition);}
Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...