我有一个同时具有navid和sub-vid的模型。在销毁模型时,我需要签入整个集合,对于其他具有与我试图删除的模型的sub-vid相同navid的模型。请帮帮我。提前谢谢。这是我的示例代码。
型号:
var Node=Backbone.Model.extend({默认值:{NavId:",SubNavId:"。项目名称:"}}
收藏:
var NodeCollection=Backbone.Collection.extend({model:Node}
我有两个视图,一个用于节点(我正在构建tr),另一个用于集合(我需要构建表)var NodeCollectionView=Backbone.View.extend({
initialize: function (options) { var self = this; self.collection = new NodeCollection({ NavigationId: options.NavigationId }); self.collection.fetch({ success: function () { /*I am getting hte proper collection from my restful api and iam able to bind it properly self.render(); } }); }, render: function () { var that = this; _.each(this.collection.models, function (item) { that.RenderEachNode(item); }, this); }, RenderEachNode: function (item) { var TempJsonNode = item.toJSON(); var self = this; var nodeView = new NodeView({ tagName: 'tr', id: 'NavId_' + TempJsonNode.NavItemId, model: item }); } });
var ItemTemplate = ""; ItemTemplate += " <td>"; ItemTemplate += " <a><%= ItemName %></a>"; ItemTemplate +=" </td>"; ItemTemplate
+=" <td>"; ItemTemplate +=" <a href='#' original-title='Delete ' class='tip_north Delete'>X</a>"; ItemTemplate +=" </td> ";
var NavigationItemView = Backbone.View.extend({
template: ItemTemplate,
render: function () {
var self = this;
var tmpl = _.template(this.template);
this.$el.html(tmpl(this.model.toJSON()));
return this;
},
events: {
"click .Delete": "DeleteBtnClick"
},
DeleteBtnClick: function () {
var self = this;
self.model.destroy({
success: function (status, data) {
var RetData = JSON.parse(data);
if (RetData.Status == 'Success') {
$(self.el).remove()
}
},
error: function () {
alert('Error In Deleting The Record');
}
});
return false;
} });
我能够正确地构建表,但在销毁模型时,我没有找到销毁依赖模型的方法。我的Api受到限制,以至于我无法获得嵌套的json(如果是这样,我会使用主干关系)。所以我需要弄清楚其他具有模型NavId的模型和视图正在删除。
请帮帮我。
像这样的东西怎么样
var NodeView = Backbone.View.extend({
initialize: function() {
//when the model gets destroyed, remove the view
this.listenTo(this.model, 'destroy', this.remove);
},
//..clip
DeleteBtnClick: function () {
var self = this;
var collection = self.model.collection;
var navId = self.model.get('NavId');
self.model.destroy({
success: function (status, data) {
var RetData = JSON.parse(data);
if (RetData.Status == 'Success') {
//if parent was part of a collection
if (collection) {
//find related models
var related = collection.filter(function (model) {
return model.get('SubNavId') === navId;
});
//call destroy for each related model.
var promises = _.invoke(related, 'destroy');
//optional: if you want to do something when all the children
//are destroyed:
$.when.apply($, promises).then(function () {
console.log('all destroyed');
});
}
}
},
error: function () {
console.log(arguments);
alert('Error In Deleting The Record');
}
});
return false;
}
});
编辑:JSFiddle此处