Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

backbone.js how to use variables as selectors in events

In Backbone.js I am trying to use a variable as a selector to bind to an event like this:

events: function() {
    var _events = {};
    _events["click " + "#plus-" + this.options.count] = "add";
    return _events;
}

Some (or more than one) thing must be wrong because Backbone seems to ignore it.

Most examples I've seen here use class and not id selectors. Is there a reason for that?

Thanks in advance

like image 313
alearg Avatar asked Feb 20 '23 12:02

alearg


1 Answers

I have to say that I don't understand this dynamic events declaration need. But I suppose you have your reasons.

Any how I've come up with a working solution that looks like this:

// html
<div id="container">
    <button id="button-1">button 1</button>
    <button id="button-2">button 2</button>
</div>​

// js
var View = Backbone.View.extend({
    events: function(){
        var _events = {};
        _events["click " + "#button-" + this.options.count] = "buttonClick";
        return _events;
    },
    buttonClick: function(){
        console.log( "click() on button " + this.options.count );
    }
});

var view1 = new View({
    el: $('#container'),
    count: 1
});


var view2 = new View({
    el: $('#container'),
    count: 2
});

Check the working jsFiddel

So, either I'm missing something or the issue is somewhere else.

About using class or id in your events css selector it is just up to you.

like image 183
fguillen Avatar answered Mar 05 '23 04:03

fguillen