JavaScript: what if nested ‘this’ doesn’t work?

Note: Examples used in that post require usage of prototype.js.

Imagine you have a JavaScript class with some features related to the current view. One of the method in that class is supposed to add an observer on all anchors marked with class “delete”. That observer is also defined in this class. In other words, you have a number of “delete” links (similar to one below) and you want to register an event handler that would fire when either of those links is clicked.

The link exmple:

<a href="#" class="delete">delete</a>

Let’s assume the aforementioned methods are defined as follows:

registerDeleteHandlers: function() {
	$$('a.delete').each(function(anchor) {
		anchor.observe('click', this.deleteItem);
	});
},
deleteItem: function(event) {
	...
}

As you would discover the handler wouldn’t be registered… It’s because this inside the inner function (which really registers the observer) is binded to a different context!

Simple solution (smarter)

Define the registerDeleteHandlers function as follows:

registerDeleteHandlers: function() {
	$$('a.delete').each(function(anchor) {
		anchor.observe('click', this.deleteItem);
	}.bind(this));
}

Another way around

Inside the registerDeleteHandlers function you can bind this to a temporary variable and use it in the inner function instead of this. So the registerDeleteHandlers function would look like that:

registerDeleteHandlers: function() {
	var self = this;
	$$('a.delete').each(function(anchor) {
		anchor.observe('click', self.deleteItem);
	});
}

0 Responses to “JavaScript: what if nested ‘this’ doesn’t work?”


  • No Comments

Leave a Reply