2

我有这个收藏:

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!?
}

我应该采取什么方法从“单位”数组中删除一个项目(单击的项目)?

4

3 回答 3

2

这是快速而肮脏的方法:

假设数组的顺序没有通过任何其他媒介改变,你可以这样做

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
}
于 2012-12-03T12:09:19.657 回答
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)。

于 2012-12-03T12:00:08.860 回答
0

据我了解,您需要从模型中删除项目

Person = Backbone.Model.extend({ initialize: function() { alert("Welcome to this world"); } }); var person = new Person({ name: "Thomas", age: 67}); delete person.name

于 2013-07-04T05:03:42.680 回答