All you have to do is add Attributes defenition to your class
var Employee = new Class({
Attributes: {
name: {
value: 'Unnamed',
validator: function(val) {
return val.trim().length > 2;
}
},
salary: {
getter: function(val) {
return this.get('currency') + val;
}
},
currency: {
value: '$'
}
},
initialize: function(attributes) {
this.setAttributes(attributes);
}
});
Now you're able to create instance with initial attributes (like options)
var bob = new Employee({
name: 'Bob',
salary: 10000
});
Add events to listen attributes changes
bob.addEvent('salaryChange', function(event) {
alert('Old salary: {oldVal}, new salary: {newVal}'.substitute(event));
});
Set attributes
bob.set('salary', 12000); // alert text: 'Old salary: 10000, new salary: 12000';
Get attributes
bob.get('salary'); // '$12000' - since we defined getter
Validate attributes
bob.set('name', 'B'); // Will not set name since we have length validator
If you try to access non-existing attribute with .get() - by it will return undefined, if try to set it .set(attr, value) - nothing will happen. But you're able to control accessing non-existing attributes by $getter and $setter that will be called for such attributes
var Employee = new Class({
Attributes: {
$getter: function(name) {
return Cookie.read(name);
},
$setter: function(name, value) {
Cookie.write(name, value)
},
name: {
value: 'Unnamed',
validator: function(val) {
return val.trim().length > 2;
}
}
}
});
...
instance.get('age'); // -> returns Cookie 'age' as we defined such behaviour at $getter
instance.set('age', 1); // -> write 'age' to Cookies
Attribute can have following properties:
Also when value is changed (in case it successfully validated) the instance fires attrChange event, e.g.: nameChange, salaryChange, etc. Event handler gets one parameter - object with newVal and oldVal properties.
A note on comments here: These comments are moderated. No comments will show up until they are approved. Comments that are not productive (i.e. inflammatory, rude, etc) will not be approved.
Found a bug in this plugin? Please report it this repository's Github Issues.
blog comments powered by Disqus