Created
June 6, 2014 16:53
-
-
Save jnwelzel/047b37d02b4ec63422ff to your computer and use it in GitHub Desktop.
Backbone mixin for enabling Reactjs components to respond to Backbone objects/collections changes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// An example generic Mixin that you can add to any component that should react | |
// to changes in a Backbone component. The use cases we've identified thus far | |
// are for Collections -- since they trigger a change event whenever any of | |
// their constituent items are changed there's no need to reconcile for regular | |
// models. One caveat: this relies on getBackboneModels() to always return the | |
// same model instances throughout the lifecycle of the component. If you're | |
// using this mixin correctly (it should be near the top of your component | |
// hierarchy) this should not be an issue. | |
var BackboneMixin = { | |
componentDidMount: function() { | |
// Whenever there may be a change in the Backbone data, trigger a reconcile. | |
this.getBackboneModels().forEach(function(model) { | |
model.on('add change remove', this.forceUpdate.bind(this, null), this); | |
}, this); | |
}, | |
componentWillUnmount: function() { | |
// Ensure that we clean up any dangling references when the component is | |
// destroyed. | |
this.getBackboneModels().forEach(function(model) { | |
model.off(null, null, this); | |
}, this); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment