Backbone.js Todo Example
HTML
<script src="https://rawgithub.com/jashkenas/underscore/1.5.2/underscore-min.js"></script>
<script src="https://rawgithub.com/jashkenas/backbone/1.0.0/backbone-min.js"></script>
<form>
<input />
<p>click a button to populate the input</p>
</form>
<p><strong>Which entity in Backbone should control this interaction?</strong></p>
<p>Have an answer for me?: <a href="http://stackoverflow.com/questions/22638431/backbone-events-scope" target="_blank">stackoverflow.com</a></p>
CSS
button { padding: 10px 30px; float: left; }
form:before, form:after { content: " "; display: table; }
form:after { clear: both; }
JavaScript
var Button = Backbone.Model.extend({
defaults: {
val: ""
}
});
var ButtonList = Backbone.Collection.extend({
model: Button
});
var ButtonView = Backbone.View.extend({
template: _.template('<button value="<%= val %>"><%= val %></button>'),
events: {
'click': 'selectDate'
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
selectDate: function(e) {
e.preventDefault();
this.trigger("clicked", this.model);
}
});
var ButtonListView = Backbone.View.extend({
className: "button-set",
render: function() {
var container = document.createDocumentFragment();
this.collection.each(function(model) {
var view = new ButtonView({
model: model
});
this.listenTo(view, "clicked", this.onButtonClicked);
container.appendChild(view.render().el);
}, this);
this.$el.empty().append(container);
return this;
},
onButtonClicked: function(button){
this.trigger("button:clicked", button);
}
});
var ButtonSetController = _.extend({
start: function(){
var buttonSetCollection = new ButtonList([{val: "A"}, {val: "B"}, {val: "C"}]),
buttonSetView = new ButtonListView({collection: buttonSetCollection});
this.listenTo(buttonSetView, "button:clicked", this.onButtonClicked);
$("form").append(buttonSetView.render().el);
},
onButtonClicked: function(button){
$("input").val(button.get("val"));
},
stop: function(){
this.stopListening();
}
}, Backbone.Events);
ButtonSetController.start();