How does a Backbone.js View know when its collection has changed?
我有一个以集合为模型的Backbone 视图。如果将集合通过其构造函数传递,则可以在其初始化函数中向该集合添加侦听器,但是如何知道构造后何时设置其集合,以便可以侦听该集合中的事件?
我希望能够在其生命周期中更改其集合,并根据新集合中的数据重新渲染它,但是似乎无法知道何时更改了它的集合?有没有可用的钩子?
[注意:请参见下面的答案,其中包含基于斯图史密斯答案的代码]
我不认为有任何自动方法可以知道-
您始终可以提供一个函数
为清楚起见,您还可以从
这是我基于stusmith的答案的解决方案:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | initialize: function(){ if(this.collection){ this.addCollectionListeners(); } }, setCollection:function(collection){ if(collection != this.collection){ if(this.collection){ this.removeCollectionListeners(); } this.collection = collection; this.addCollectionListeners(); } }, removeCollectionListeners:function(){ //Remove listeners }, addCollectionListeners:function(){ //Add listeners }, |