I've been working with some event handling in Javascript and recently decided to migrate from Prototype to jQuery. I already encountered some trouble using Prototype, but found some workarounds which at least solved the problems, but didn't look very nice to me. Now I'm rewriting everything anyway, I'd like to get it all straight on the go. If possible, I'd like to hear your advice on some 'best practices' concerning this issue.
Short description: I built an 'objectList' prototype, which allows you to select an item (which, in turn, sets some other stuff in motion). To make life easier, it employs a 'searchList' (another prototype I wrote) which allows you to do incremental search filtering and live sorting on the listed items. The searchlist is a member of the objectlist, as visible in the code below. If an item is clicked, the searchlist triggers a (custom) event, to which the objectlist should then respond. Right now, I use this approach:
var self = this;
$(this.searchList).bind('objectSelected', function() {
self.selectObject(self.searchList.getSelectedId());
});
In Prototype, I used to bind()
the callback to this
, so that I'd be able to access the same this
from there (http://stackoverflow.com/questions/520019/controlling-the-value-of-this-in-a-jquery-event). However, jQuery doesn't seem to have native scope binding support, and probably for a reason. The 'self
-approach' does work, but I was wondering whether this is considered 'good code', or that it probably is an omen of bad program design.
Furthermore, I sometimes used to make the callback a member of the 'parent' object, like this (note: Prototype-syntax):
init: function() {
var self = this;
this.searchList.observe('objectWasSelected', this.objectSelected.bind(this));
}
objectSelected: function() {
this.selectObject(this.searchList.getSelectedId());
}
but after thinking about it, it seemed superdumb. So, core question: is my new approach (topmost code, using self
) really better, and more importantly, is there still a better one? Always looking to improve my skills, especially regarding good program design, so if anyone would be able to shine a light on this, I'd be very grateful!