我有这个系列:
var items = new bb.Collections.QuotesCollection([
{id: 1, name: "item 1", units: []},
{id: 2, name: "item 2", units: []},
{id: 3, name: "item 3", units: []}
]);
然后我像这样输出数组“单位”:
if(this.model.get('units').length){
$(this.el).append('<strong>Units</strong>');
$(this.el).append('<ul>');
for(x in this.model.get('units')){
$(this.el).append('<li class="unit">' + this.model.get('units')[x] + '</li>');
}
$(this.el).append('</ul>');
}
上面的代码只是POC的东西,所以还没有正式的模板。
events: {
"keypress #addUnit" : "addUnit",
"dblclick .unit" : "deleteUnit"
},
deleteUnit: function(){
this.render(); // what do I put here!?
}
从“units”数组中删除项目(点击的项目)需要采取什么方法?
答案 0 :(得分:2)
这是快速而肮脏的方法:
假设Array的顺序没有通过任何其他介质更改,您可以
deleteUnit: function() {
// get the index of the li you are clicking
var index = $('.unit').index(this);
this.model.get('units').splice(index, 1);
this.render();
}
这样你就必须记得在每次渲染之前清空你的视图元素
render: function() {
this.$el.empty();
...
// business as usual
}
答案 1 :(得分:1)
首先,您可能希望每个模型都有一个视图对象,因此您拥有一个拥有<ul>
的集合视图,如下所示:
var ParentView = Backbone.View.extend({
render: function() {
var html = '<ul></ul>'; // make your html here (usually with templates)
this.$el.append(html);
this.collection.each(_.bind(this.initChild, this));
return this; // so we can chain calls if we want to.
}
initChild: function(model) {
var child = new ChildView({ model: model });
// this.$() is scoped to the view's el property
this.$('ul').append(child.render().el);
}
});
然后你可以设置这样的子视图:
var ChildView = Backbone.View.extend({
events: { 'click .delete', 'deleteModel' },
render: function() {
var html = '';// make your html here (usually with templates)
this.$el.append(html);
return this;
},
deleteModel: function(ev){
ev.preventDefault();
// Removes form the collection and sends an xhr DELETE
this.model.destroy();
this.$el.remove();
}
});
对Model#destroy的调用将负责将其从集合中删除并向服务器发送DELETE(假设您在集合/模型中设置了URL)。
答案 2 :(得分:0)
据我了解,您需要从模型中删除项目
Person = Backbone.Model.extend({
initialize: function() {
alert("Welcome to this world");
}
});
var person = new Person({ name: "Thomas", age: 67});
delete person.name