Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Configurable Backbone.js events selectors

I'm working on simple application with excelent framework Backbone.js and it will be nice if I could make configurable backbone view events selector for example this way it doesn't work, cause it's wrong js syntax:

return Backbone.View.extend({
    events: {
        'click ' + someConfigSelector: 'doSomethink'
    }
})

Is there any other way to setup events in Backbone views?

like image 452
Karol F Avatar asked Feb 17 '23 03:02

Karol F


2 Answers

Check out this fiddle: http://jsfiddle.net/phoenecke/hyLMz/1/

You can use a function for events instead of an object.

return Backbone.View.extend({
    events: function() {
        // add some normal events to the hash
        var e = {
            'click #foo': 'doSomething1',
            'click #bar': 'doSomething2'
        };
        // add one where key is calculated
        e['click ' + someConfigSelector] = 'doSomething';
        // return events hash
        return e;
    }
});

That way, you can add your events where the key is calculated based on your config.

like image 188
Paul Hoenecke Avatar answered Mar 11 '23 19:03

Paul Hoenecke


I prefer the method below for dynamic events, as this function will be called any time delegateEvent is called.

Per the docs on delegateEvent, which is called after the view's initialize function is executed, you can use this technique to create the events dynamically:

var TestView = Backbone.View.extend({    
    events: function () {
        var evt = {};
        evt['click ' + this._extraSelector] = '_onButtonClick';
        return evt;
    },
    initialize: function(config) {
        // passed in the selector, or defaulted 
        this._extraSelector = config.extraSelector || "BUTTON.default";
    }, 

    _onButtonClick: function() { }
});

var v = new TestView({ extraSelector: 'BUTTON.sample' });
like image 44
WiredPrairie Avatar answered Mar 11 '23 17:03

WiredPrairie