我有一个计数器(产品数量),我想使用骨干JS自定义事件进行操作。如果单击添加产品,则产品号应增加;如果单击删除产品,则产品号应减少一。Demo here问题是,当我单击按钮时,计数器的值未得到更新。 这是代码段
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 });
HTML代码为:
<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>
答案 0 :(得分:1)
这是一个有效的示例:https://codepen.io/tilwinjoy/pen/OJPyNbR?page=1&
问题很少:
<span>
,而且一切都在外面。答案 1 :(得分:1)
以下代码将通过测试用例解决问题,但是,如果您在浏览器中运行它,它将无法工作,但是谁在乎这有助于清除测试;) 只是修改了代码来清除测试用例。
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 });