Search code examples
javascriptjqueryeventsobject-literal

Can a Javascript literal object fire events?


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?


Solution

  • This should work:

    var Toolbar = {
    
        init: function(toolbar) {
            this.Bar = $(toolbar); // scope is Toolbar object literal
    
            this.Bar.find('.clearButton').click($.proxy(function() {
                $(this).trigger('clear'); // should work now
                this.Bar.trigger('clear'); // still works
            }, this));
        }
    };
    
    Toolbar.init($('div.toolbar'));
    
    $(Toolbar).bind('clear', function() { 
        console.log('Toolbar'); 
    }); // should work now
    
    Toolbar.Bar.bind('clear', function() { 
        console.log('Toolbar.Bar'); 
    }); // still works
    
    1. You need to maintain the this reference in the click function. I used $.proxy; some folks use var self = this;

    2. Toolbar is not a jQuery object so it should be wrapped in $() to access jQuery's functions. Also wrap the this that refers to a Toolbar instance in the click function.