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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With