This repository has been archived by the owner on Oct 11, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
Bound Model Collection Hooks
buttondownben edited this page Oct 16, 2013
·
8 revisions
Hooks into a change in the model or collection associated with your component are a very powerful thing. You can update the UI, cache some data, or perform many other useful actions. If you bind a model or collection to a component by defining this.model
or this.collection
you can tap into lifecycle changes in these data structures.
Handlers can be written to respond to changes in the component's model. Just define the afterChange
function in your component.
Mast.define('Person', function () {
return {
beforeRender: function() {
this.model = new Mast.Model.extend({name:'Joe', age:'25'});
}
// Define afterChange as a function that is called when the model is changed.
afterChange: function(model, options) {
// write some code that can use the updated model and options passed to that change.
...
}
};
});
You can also define afterChange
as a hash that contains methods called when a certain model attribute is changed.
Mast.define('Person', function () {
return {
...
// Define afterChange as a hash with handlers that are called when that attribute is changed.
// All handlers passed the new value that the attribute was changed to.
afterChange: {
name: function (newVal) {
// some code that does something when the model's `name` attribute is changed.
...
},
age: function (newVal) {
// some code that does something when the model's `age` attribute is changed.
...
}
}
};
});
Component collections also have hooks when models are being added, removed, and/or reset on the collection performed. These hooks are afterAdd
, afterRemove
, and afterReset
.
Mast.define('PhoneBook', function () {
return {
beforeRender: function() {
this.collection = new Mast.Collection.extend({model: Contact});
},
...
// Is called whenever a model is added to the components bound collection.
afterAdd: function(model, collection, options) {
...
},
// Is called whenever a model is removed from the components bound collection.
afterRemove: function(model, collection, options) {
...
},
// Is called whenever the component's bound collection is reset.
afterReset: function(collection, options) {
...
}
};
});