Custom Backbonejs Events(increment And Decrement) Not Working
I am having a counter(No. of products) that I want to manipulate using backboneJS custom events. If I click Add Product then No. of products should increase by and if I click Remov
Solution 1:
Here's a working example: https://codepen.io/tilwinjoy/pen/OJPyNbR?page=1&
There was few issues:
- The elements you are trying to bind events to has to be inside the view. In your case view element was only a
<span>
and everything was outside. - Backbone doesn't have two way binding (though there are extensions that can bring such ability) so after updating the model you have to re-render the view yourself
Solution 2:
The following code will fix the issue with a test case, however, it won't work if you run it in the browser, but who cares when this helps to clear the test ;) Just modified the code to clear the test case.
var Counter = Backbone.Model.extend({
defaults: { no_of_products: 10 }
});
var cnt = new Counter();
// ------- view -------var AppView = Backbone.View.extend({
el:'#product_details',
render: function() { this.$('#no_of_products').html(this.model.get('no_of_products'));
},
events:{
'click .add-one': 'addOne',
'click .minus-one': 'minusOne'
},
initialize: function() {
this.model.on('change', this.render, this);
this.render();
},
// view methods
addOne: function() {
this.model.set({no_of_products: this.model.get('no_of_products')+1});
this.render();
},
minusOne: function() {
this.model.set({no_of_products: this.model.get('no_of_products')-1});
this.render();
}
});
var view = new AppView({ model: cnt });
Post a Comment for "Custom Backbonejs Events(increment And Decrement) Not Working"