Skip to content

Commit c7d2760

Browse files
committed
Move backbone integration into its own mixin
1 parent 875782c commit c7d2760

File tree

1 file changed

+25
-5
lines changed
  • examples/todomvc-backbone/js

1 file changed

+25
-5
lines changed

examples/todomvc-backbone/js/app.js

Lines changed: 25 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -128,14 +128,34 @@ var TodoFooter = React.createClass({
128128
}
129129
});
130130

131+
// An example generic Mixin that you can add to any component that should react to changes in a Backbone component.
132+
// The use cases we've identified thus far are for Collections -- since they trigger a change event whenever
133+
// any of their constituent items are changed there's no need to reconcile for regular models.
134+
// One caveat: this relies on getBackboneModels() to always return the same model instances throughout the
135+
// lifecycle of the component. If you're using this mixin correctly (it should be near the top of your
136+
// component hierarchy) this should not be an issue.
137+
var BackboneMixin = {
138+
componentDidMount: function() {
139+
// Whenever there may be a change in the Backbone data, trigger a reconcile.
140+
this.getBackboneModels().map(function(model) {
141+
model.on('add change remove', this.forceUpdate, this);
142+
}.bind(this));
143+
},
144+
componentWillUnmount: function() {
145+
// Ensure that we clean up any dangling references when the component is destroyed.
146+
this.getBackboneModels().map(function(model) {
147+
model.off(null, null, this);
148+
}.bind(this));
149+
}
150+
};
151+
131152
var TodoApp = React.createClass({
153+
mixins: [BackboneMixin],
132154
getInitialState: function() {
133155
return {editing: null};
134156
},
135-
// Here is "the backbone integration." Just tell React whenever there *might* be a change
136-
// and we'll reconcile.
137157
componentDidMount: function() {
138-
this.props.todos.on('add change remove', this.forceUpdate, this);
158+
// Additional functionality for todomvc: fetch() the collection on init
139159
this.props.todos.fetch();
140160
},
141161
componentDidUpdate: function() {
@@ -145,8 +165,8 @@ var TodoApp = React.createClass({
145165
todo.save();
146166
});
147167
},
148-
componentWillUnmount: function() {
149-
this.props.todos.off(null, null, this);
168+
getBackboneModels: function() {
169+
return [this.props.todos];
150170
},
151171
handleSubmit: React.autoBind(function() {
152172
var val = this.refs.newField.getDOMNode().value.trim();

0 commit comments

Comments
 (0)