问题
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 Remove Product then No. of products should decrease by one.Demo here The problem is, value of counter is not getting updated when i click buttons. here is code snippet
var Counter = Backbone.Model.extend({
defaults: { value: 10 },
// model methods
increment: function() {
this.set({value: this.get('value')+1});
},
decrement: function() {
this.set({value: this.get('value')-1});
}
});
var cnt = new Counter();
// ------- view -------
var AppView = Backbone.View.extend({
el:'#no_of_products',
render: function() {
this.$el.html(this.model.get('value'));
},
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.increment();
},
minusOne: function() {
this.model.decrement();
}
});
var view = new AppView({ model: cnt });
And html code is:
<div id="product_details">
<h1>No of Products:<span id="no_of_products">0</span></h1>
<table>
<tr>
<td>
Add Product
</td>
<td>
: <button class="add-one">+1</button>
</td>
</tr>
<tr>
<td>
Remove Product
</td>
<td>
: <button class="minus-one">- 1</button>
</td>
</tr>
</div>
回答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
来源:https://stackoverflow.com/questions/59116014/custom-backbonejs-eventsincrement-and-decrement-not-working