[英]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.我有一个计数器(产品数量),我想使用 backboneJS 自定义事件进行操作。 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:而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>
Here's a working example: https://codepen.io/tilwinjoy/pen/OJPyNbR?page=1&这是一个工作示例: https ://codepen.io/tilwinjoy/pen/OJPyNbR?page=1&
There was few issues:有几个问题:
<span>
and everything was outside.在您的情况下,视图元素只是一个<span>
并且一切都在外面。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 });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.