使用cid删除Backbone.js模型

时间:2013-09-28 17:11:45

标签: javascript jquery json backbone.js jasmine

我正在尝试删除我在骨干网中创建的模型。我并没有试图取消模型本身。

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

    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 个答案:

答案 0 :(得分:1)

  1. 您在使用Container时似乎滥用了Backbone模型。将盒子视为具有自己模型的视图,以及将容器分配给它的视图容器并通过创建然后管理盒子进行迭代将是更好的做法。您可以将侦听器分配给集合以选择何时删除框。

  2. 您拨打myContainer.deleteBox(myBox);,但不接收作为参数传递的方框!

  3. 更新

    在回应你的笔记时,我明白了 - 它需要一些包装才能习惯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();
    

    这有帮助吗?