I’m starting to learn Backbone with this simple example:
<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($)
So when the “Add” button is pressed the counter should increase and the view should be updates. I have binded the view and the model and have the click event linked with the add function, but somehow this is not working.
So I guess I’m doing something wrong or I’m just missing some binding?
EDIT: Fixed as suggested to this … still not working:
<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($)
EDIT: FIXED AND WORKING
<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>
The button must be a descendant of the view’s
elUpdate your html like below and it should work
If you still want to display the count, then add an additional
spanAnd update your render method