Backbone.accessors generates accessors from the fields of a Backbone.js model. For each field
unsetXXX() methods are added. For clarity and readability, the first letter of each
XXX filed is converted to uppercase.
|Without accessor:||With accessor:|
This plugin is compatible with AMD provided the proper shim is added.
This approach is inspired by Propel, an Object-Relational Mapping (ORM) for PHP.
Include Backbone in your project before including the Backbone.accessors plugin.
In your models, add all fields requiring accessors to the
defaultsobject. Set the value to
undefinedwhere no default value is desired:
1 2 3 4 5 6 7 8
- Apply the accessor mixin to each model.
- Use your model normally, replacing the calls to
unset()with the custom ones:
1 2 3 4
Note: you can mix both types of accesors.
One solution is to populate and use a constant object, an approach commonly used in strongly-typed languages such as Java and C#:
1 2 3 4 5 6 7 8 9
While intended to generate an error if there is a typo in
Constants.NameModel.firstName, this approach will fail silently if the last identifier of the notation (in practice the most complex) has a mistake in it:
On the other hand, with accessors, there is less code to type, no constant file to carry around, and the code will immediately fail (fail hard) if there is a typo in the variable name:
See the included README file for more information.
You can get the code on GitHub.