Javascript 更新/破坏我的观点,我相信我的逻辑可能需要注意
我有一个从VeriousAPI中提取播客的主干项目 我要解决的问题是删除当前显示的所有视图。我希望通过将事件绑定到单击移除锚定时激发的每个视图来实现这一点 目前集合重置触发并删除所有模型,但我无法确保视图也被销毁。我想我的逻辑需要帮助 这是我的密码:Javascript 更新/破坏我的观点,我相信我的逻辑可能需要注意,javascript,backbone.js,underscore.js,Javascript,Backbone.js,Underscore.js,我有一个从VeriousAPI中提取播客的主干项目 我要解决的问题是删除当前显示的所有视图。我希望通过将事件绑定到单击移除锚定时激发的每个视图来实现这一点 目前集合重置触发并删除所有模型,但我无法确保视图也被销毁。我想我的逻辑需要帮助 这是我的密码: podSearch = Backbone.Model.extend(); podSearchCollection = Backbone.Collection.extend({ model: podSearch, parse: fun
podSearch = Backbone.Model.extend();
podSearchCollection = Backbone.Collection.extend({
model: podSearch,
parse: function(response) {
return response.results;
}
});
ownerList = Backbone.Model.extend();
ownerListCollection = Backbone.Collection.extend({
model: ownerList,
parse: function(response) {
return response.results;
}
});
Search = Backbone.View.extend({
initialize: function(){
this.searchCollection = new podSearchCollection();
this.searchCollection.bind('reset', this.appendResult, this);
},
events: {
"click button" : "getTerm"
},
doSearch: function(term){
/* get term and collection url */
this.searchCollection.fetch();
},
appendResult: function(){
_.each(this.searchCollection.models, function (item) {
var listItem = new ownerItem({model:item});
$('#results').append(listItem.render().el);
});
},
removeAll: function(){
console.log(this.searchCollection);
this.searchCollection.reset();
}
});
ownerItem = Backbone.View.extend({
template: $("#castOwner").html(),
initialize: function(){
this.ownerListCollection = new ownerListCollection();
this.ownerListCollection.bind('reset', this.appendResult, this);
this.model.bind("reset", this.removeSelf);
},
render: function(){
var tmpl = _.template(this.template);
this.$el.html( tmpl( this.model.toJSON() ) );
return this;
},
events: {
"click a" : "pullCasts",
"click a.removeAll" : "removeAll"
},
pullCasts: function(e){
e.preventDefault();
var id = this.$el.find('a').attr("href");
this.ownerListCollection.url = 'http://itunes.apple.com/lookup?id=' + id + '&entity=podcast&callback=?';
this.ownerListCollection.fetch();
},
appendResult: function(){
_.each(this.ownerListCollection.models, function(item){
/* do something with each item */
}, this);
$(this.el).append('<p><a href="#" class="removeAll">Remove All</a></p>');
},
removeAll: function(){
search.removeAll();
},
removeSelf: function(){
console.log("rm");
}
});
search = new Search();
为了在模型被破坏时删除视图,您可以向视图中添加一个侦听器,如果模型被破坏,该侦听器将删除视图:- 初始化:函数{ //如果模型发生更改,视图将重新渲染 this.model.onchange,this.render,this; //如果模型被破坏,视图将被删除 this.model.ondestory,this.remove,this },
我认为我们可以为您的问题提供适当的答案,但我认为您应该努力从示例中删除任何不相关的代码,并尝试以一种更抽象的方式描述您的问题,即个人商业模式不可知。我认为仅仅复制/粘贴你非常个人化的商业模式是不礼貌的。提供一个简化的、以问题为中心的问题将有助于构建更多可重复使用的答案。好的,我现在明白了。在未来,我将确保创建一个更通用的版本来演示我的问题。