简体   繁体   中英

How does a Backbone.js View know when its collection has changed?

I have a Backbone View that has a Collection as its Model. If the collection is passed in through its constructor it can add listeners to the collection in its initialize function, but how can it know when its collection is set after construction so that it can listen to events from the collection?

I want to be able to change its collection during its lifecycle and have it re-render based on the data in the new collection, but there seems to be no way of it knowing when its collection has changed? Are there any hooks available?

[Note: See my answer below with code based on stusmith's answer]

I don't think there is any automatic way to know - collection is just an ordinary property.

You could always provide a function setCollection instead, which unbinds events from the old collection (if any), assigns the collection, and rebinds to the new one.

For clarity, you would also call this function from initialize .

Here is my solution based on stusmith's answer:

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
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM