Вот пример событий между двумя представлениями, работающими с моделью / коллекцией.В основном, используйте collectionName.bind ('add', yourFunction, this);
<script type="text/template" id="item-template">
<div class="nonedit"><span ><%= name %> (<%= age %>)</span> <a class="delete" href="#">X</a>
<div class="edit"><input /></div>
</script>
<body>
<ul class="1"></ul>
<div class="count">
<div></div>
<input id="name" placeholder="enter a name"/>
<input id="age" placeholder="enter age"/>
</div>
</body>
var Person = Backbone.Model.extend({
defaults:function(){
return {
name:'unknown',
age:0
};
}
});
var People = Backbone.Collection.extend({
model:Person
});
var people = new People;
var Li = Backbone.View.extend({
tag:'li',
class:'name',
template:_.template($('#item-template').html()),
events:{
'click a.delete':'remove'
},
initialize:function(){
this.model.bind('change',this.render,this);
$(this.el).html(this.template(this.model.attributes));
},
render:function(){
$(this.el).html(this.template(this.model.attributes));
},
remove:function(){
this.model.destroy();
$(this.el).fadeOut(300);
setTimeout(function(){$(this.el).remove()},400);
},
modify:function(){
$(this.el).addClass('edit');
}
});
var Ul = Backbone.View.extend({
el:$('ul'),
events:{
},
initialize:function(){
people.bind('add',this.add,this);
},
render:function(){
},
add:function(model){
var li = new Li({model:model});
this.el.append(li.el);
}
});
var ul = new Ul;
var Div = Backbone.View.extend({
el:$('.count'),
nameInput:$('#name'),
ageInput:$('#age'),
events:{
'keypress input#name':'keypress',
'keypress input#age':'keypress',
},
initialize:function(){
people.bind('add',this.add,this);
},
render:function(){
},
add:function(e){
this.el.find('div').html(people.length);
},
keypress:function(event){
if(event.which == 13){
people.add({name:this.nameInput.val(),age:this.ageInput.val()});
}
}
});
var div = new Div;