删除骨干.js带有 cid 的模型
Deleting Backbone.js models with cid
我正在尝试删除我在骨干中创建的模型。我并不是要取消模型本身。
这就是我所拥有的:首先对代码进行茉莉花单元测试
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 处的对象。我不知道该怎么做。有什么建议吗?
-
看起来您在使用容器时滥用了主干模型。更好的做法是使框成为具有自己的模型的视图,使容器成为分配有框集合的视图,并循环访问创建和管理框的过程。可以将侦听器分配给集合以选择何时删除框。
-
您调用
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();
这有帮助吗?
相关文章:
- 在VanillaJS中模拟模型双向数据绑定
- 为集合分配大量的模型弹药
- 如何使用backbone.js从集合中获取模型名称
- 骨干模型默认值-todos.js示例中不必要的代码
- EmberJS中支持单字母单词模型
- 2个backbone.js集合,具有相同的模型,但排序顺序不同
- 将不在模型中的数据返回到mvc控制器
- 如何在视图模型contet更新更新上调用Jquery函数
- 如何使用Javascript客户端对象模型检索Sharepoint 2010列表项权限
- 我应该如何检查主干.主干.模型更改时查看
- Ext.js从json构建模型关系的问题
- 显示模块模式在Knockout中设置模型的新实例
- 使用导航属性创建Kendo UI网格模型的问题
- 在Backbone中通过CID设置和获取模型
- 删除骨干.js带有 cid 的模型
- 是否可以使用主干模型的 cid 作为 html id 属性?它是否保证是独一无二的
- Backbone.js:cid仅用于模型
- 在模板上呈现主干集合时,无法获取模型的cid
- CID无法获取主干集合中的模型
- 在 Backbone 中查找模型.js按 cid 而不是 id 收集