Skip to content

Instantly share code, notes, and snippets.

@jnwelzel
Created June 6, 2014 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnwelzel/047b37d02b4ec63422ff to your computer and use it in GitHub Desktop.
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
// 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