[英]backbone.js update one view based on events in another?
我有以下HTML代码:
<ul id='item-list'></ul>
<button id='add-item'>Add Item</button>
<script type='text/template' id='item-template'>
<li><%= title %></li>
</script>
和以下javascript / backbone js代码:
var Item = Backbone.Model.extend({});
var ItemCollection = Backbone.Collection.extend({
model: Item
});
var ItemListView = Backbone.View.extend({
el : $("#item-list"),
initialize(options) {
this.item_collection = new ItemCollection();
},
appendItem: function() {
new_item = new Item({'title' : 'New Item'});
this.item_collection.add(new_item);
item_template = $("#item-template");
item_html = _.template(item_template,new_item.toJSON());
this.el.append(item_html);
}
});
var AddItemView = Backbone.View.extend({
el: $("add-item"),
events: {
"click" : "addItem"
},
addItem: function() {
// ?
}
});
item_list_view = new ListItemView();
add_item_view = new AddItemView();
如何在addItemView视图中的事件中将新项添加到项列表视图和集合中? 另外,是否应该创建模型,将其附加到集合中,并将其附加到视图中,所有这些都发生在ListItemView.addItem()
函数中,还是应该将它绑定到ItemCollection的add事件? 我仍然在绕着绑定方式缠绕我的头时遇到一些麻烦,各种视图,模型和集合之间的交互应该起作用。
这是一个使用模型/集合的2个视图之间的事件示例。 基本上,使用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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.