I have a Javascript object literal:
var Toolbar = {
init: function(toolbar) {
this.Bar = $(toolbar); // scope is Toolbar object literal
this.Bar.find('clearButton').click(function() {
this.trigger('clear'); // doesn't work!
this.Bar.trigger('clear'); // works!
}
}
Toolbar.init($('div.toolbar'));
Toolbar.bind('clear', function() { ... }); // doesn't work!
Toolbar.Bar.bind('clear', function() { ... }); // works!
I’d like to be able to trigger the clear event on the Toolbar object literal rather than the toolbar DOM object referenced in the literal. Is this possible, and if so, how would I do it?
This should work:
You need to maintain the
thisreference in the click function. I used$.proxy; some folks usevar self = this;Toolbaris not a jQuery object so it should be wrapped in$()to access jQuery’s functions. Also wrap thethisthat refers to aToolbarinstance in the click function.