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 –
collectionis just an ordinary property.You could always provide a function
setCollectioninstead, 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.