binding functions

I’ve been working on a Space Invaders style game with the request from the client that it be “developed in HTML5 and works in IE8”.(!!) A bit of a contradiction in terms. Google Chrome Frame seemed like a possible solution until they told me that no new software/plugins could be installed(and it’s goodbye to chrome frame anyway shortly).

I decided in the end to just set up two versions, one in JavaScript and the other in ActionScript. Was quite an interesting exercise, examining the similarities and differences between them. I may write more about general differences in a later post. But one difference is worth its own post:

bind(this)

For an event handler to retain its scope, you need to specify its scope, for example:

this.getStage().addEventListener('click', this.onMouseDown.bind(this));

But what this actually does is replicate the function bound to the instance. Even if the function is part of the object, it doesn’t retain its scope.

This took me a while to work out, but if you try to remove the event listener, neither of the following two lines work:

this.getStage().removeEventListener('click', this.onMouseDown);
this.getStage().removeEventListener('click', this.onMouseDown.bind(this));

Because neither of them actually refer to the original function created by the bind function, you need to actually create a new variable to begin with, containing the bound function, and then later when removing the event listener, refer to this variable:

this.onMouseDownBound = this.onMouseDown.bind(this);
this.getStage().addEventListener('click', this.onMouseDownBound);
...
this.getStage().removeEventListener('click', this.onMouseDownBound);

Interactive developer, Author - iOS development with Swift - book coming 2017 https://manning.com/books/ios-development-with-swift

Tagged with: ,
Posted in JavaScript

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: