The library for web and native user interfaces.
Move backbone integration into its own mixin
petehunt committed
May 30, 2013 at 04:35 UTC
c7d2760521066f07afb36d9e1053bb44e9da8a71
1 file changed
+25
-5
examples/todomvc-backbone/js/app.js
+25
-5
@@ -128,14 +128,34 @@ var TodoFooter = React.createClass({
128
}
129
});
130
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
+
152
var TodoApp = React.createClass({
153
+ mixins: [BackboneMixin],
154
getInitialState: function() {
155
return {editing: null};
156
},
135
- // Here is "the backbone integration." Just tell React whenever there *might* be a change
136
- // and we'll reconcile.
157
componentDidMount: function() {
138
- this.props.todos.on('add change remove', this.forceUpdate, this);
158
+ // Additional functionality for todomvc: fetch() the collection on init
159
this.props.todos.fetch();
160
},
161
componentDidUpdate: function() {
@@ -145,8 +165,8 @@ var TodoApp = React.createClass({
165
todo.save();
166
});
167
},
148
- componentWillUnmount: function() {
149
- this.props.todos.off(null, null, this);
168
+ getBackboneModels: function() {
169
+ return [this.props.todos];
170
},
171
handleSubmit: React.autoBind(function() {
172
var val = this.refs.newField.getDOMNode().value.trim();