删除骨干.js带有 cid 的模型

Deleting Backbone.js models with cid

本文关键字:cid 模型 带有 js 删除      更新时间:2023-09-26

我正在尝试删除我在骨干中创建的模型。我并不是要取消模型本身。

这就是我所拥有的:首先对代码进行茉莉花单元测试

    it("should delete the current Box ", function () {
        var myContainer = new App.Container();
        var myBox = new App.Box();
        myBox.setTitle("The First Box");
        expect(myBox.attributes.title).toBeDefined();
        **myContainer.deleteBox(myBox);**
        expect(myBox.attributes.title).toBeUndefined();
    });

现在的代码:

App.Container = Backbone.Model.extend({
    defaults: {
        type: "1.0",
        selectedBox: 0,
        boxes: [],
        labels: [],
    },
    deleteBox: function () {
        this.destroy({
            success: function() {
                console.log("the box has been removed");
                //Array reindexed
            }
        });
    }
});

它不起作用。 茉莉花单元测试失败,我想我必须如何删除主干给出的 cid 处的对象。我不知道该怎么做。有什么建议吗?

  1. 看起来您在使用容器时滥用了主干模型。更好的做法是使框成为具有自己的模型的视图,使容器成为分配有框集合的视图,并循环访问创建和管理框的过程。可以将侦听器分配给集合以选择何时删除框。

  2. 您调用myContainer.deleteBox(myBox);,但随后没有收到作为参数传递的框!

更新

作为对您的说明的回应,我确实理解 - 确实需要一些头巾才能习惯 Backbone 中的概念。

如果我理解您要做什么,这里有一些示例代码,您可以咀嚼一些示例代码,可以更好地了解如何完成此类事情:

App.Boxes = Backbone.Collection.extend({}) 
App.Box = Backbone.View.extend({});        // Child view for each model
App.Container = Backbone.View.extend({     // 'Collection view', that draws 
                                           // each child view.
  tagName: 'div',
  
  initialize: function(){
    
    this.boxes = {};
    // Assign event listeners to redraw DOM when your models change.
    this.listenTo(App.boxes, 'add', this.addBox);
    this.listenTo(App.boxes, 'remove', this.removeBox);
    
  },
  
  // Create a new box when a new model is added to the collection.
  addBox: function(model) {
    var newBox = new App.Box({ model: model });
    this.boxes[model.cid] = newBox;
    this.$el.append(newBox.render().el);
    },
  
  // Remove a box when a model is removed from the collection.
  removeBox: function(model) {
    var box = this.boxes[model.cid];
    box.remove();
  },
  
});
// Let's make the parent view.
var myContainer = new App.Container();
$(body).append(myContainer.render().el);
// Make a new collection
App.boxes = new App.Boxes();
// Add models to the collection
App.boxes.add({ title: 'The First Box', });
App.boxes.add({ title: 'The Second Box', });
// Remove a model from the collection.
App.boxes.findWhere({ title: 'The First Box' }).remove();

这有帮助吗?