-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBackboneMixin.js
66 lines (60 loc) · 1.96 KB
/
BackboneMixin.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
var BackboneMixin = {
resolveModels: function () {
var models = [];
var name = this.constructor.displayName || "ANNOYMUS";
if (typeof this.getBackboneModels === "function") {
var manualModels = this.getBackboneModels();
if (Object.prototype.toString.call(manualModels) !== "[object Array]") {
console.warn(
"Component " + name + " needs to return an Array, not an " +
typeof manualModels + ", for BackboneMixin to work."
);
} else {
// filter out undefined/null's
models = manualModels.filter(function (model) {
if (model != null) {
return model;
}
});
}
} else {
console.warn(
"Please implement 'getBackboneModels' in component " + name +
", for BackboneMixin to work."
);
}
return models;
},
// Binds a listener to a component's resource so the component can be updated
// when the resource changes.
//
// An object that uses this mixin must implement `getBackboneModels` and
// return an array of objects that extends `Backbone.Events`.
// Common use cases are `Backbone.Model` and `Backbone.Collection`.
componentDidMount: function () {
this._boundForceUpdate = this.forceUpdate.bind(this, null);
var models = this.resolveModels();
models.forEach(function (model) {
// There are more events that we can listen on. For most cases, we're
// fetching pages of data, listening to add events causes superfluous
// calls to render.
model.on(
"batch reset sync invalid change",
this._boundForceUpdate,
this
);
model.fetch({ reset: true });
}, this);
},
componentWillUnmount: function () {
var models = this.resolveModels();
models.forEach(function (model) {
model.off(
"batch reset sync invalid change",
this._boundForceUpdate,
this
);
}, this);
}
};
module.exports = BackboneMixin;