我开始用这个简单的例子来学习 Backbone:
<div id="counter">unkown</div>
<button id="add-button">ADD</button>
(function($){
var Counter = Backbone.Model.extend({
defaults: {
count: 0
}
});
var CounterView = Backbone.View.extend({
el: "#counter",
events: {
"click #add-button": "add"
},
add: function() {
this.model.count++;
render();
},
render: function() {
$(this.el).text(this.model.get("count"));
return this;
},
initialize: function(){
this.render();
}
});
var counterItem = new Counter();
var counterView = new CounterView({model: counterItem});
}(jQuery)); // function($)
因此,当按下“添加”按钮时,计数器应该会增加并且视图应该会更新。我已经绑定了视图和模型,并将点击事件与添加功能链接起来,但不知何故这不起作用。
所以我想我做错了什么或者我只是缺少一些约束力?
编辑:已按照建议修复...仍然无法正常工作:
<div class="list">
<div id="counter">unkown</div>
<button id="add-button">ADD</button>
</div>
(function($){
var Counter = Backbone.Model.extend({
defaults: {
count: 0
}
});
var CounterView = Backbone.View.extend({
el: "#counter",
events: {
"click #add-button": "add"
},
add: function() {
alert("ADD");
this.model.set("count", this.model.get("count") + 1);
this.render();
},
render: function() {
$(this.el).text(this.model.get("count"));
return this;
},
initialize: function(){
this.render();
}
});
var counterItem = new Counter();
var counterView = new CounterView({model: counterItem});
}(jQuery)); // function($)
编辑:固定和工作
<div id="counterHolder">
<div id="counter">
<span>unknown</span>
<button id="add-button">ADD</button>
</div>
</div>
<script>
(function($){
var Counter = Backbone.Model.extend({
defaults: {
count: 0
},
increase: function(){
this.set("count", this.get("count") + 1);
}
});
var CounterView = Backbone.View.extend({
el: "#counter",
events: {
"click #add-button": "add"
},
add: function() {
this.model.increase();
},
render: function() {
$("#counter span").text(this.model.get("count"));
return this;
},
initialize: function(){
this.render = _.bind(this.render, this);
this.render();
this.model.bind('change:count', this.render);
}
});
var counterItem = new Counter();
var counterView = new CounterView({model: counterItem});
}(jQuery)); // function($)
</script>