Creating Models becomes much easier with the Base Model.
In this example I will walk through some of the default conventions and requirements for creating such a model.
Creating Models becomes much easier with the Base Model.
In this example I will walk through some of the default conventions and requirements for creating such a model.
| ((Models) -> | |
| Models.Client = Models.Base.extend | |
| someCode: -> | |
| )(Application.Models) | |
| #In the above code the model extends base by calling Models.Base.Extend | |
| #At a minimum this is what is needed to create a base Model |
| #base also ensures that all nested models and collections are properly created in both parse and initialize | |
| #client.js.coffee | |
| #just declare collections with has_many and the attribute name | |
| #and models with has_one and the attribute name | |
| has_many: ["email_addresses", "addresses", "phone_numbers"] | |
| #if the attribute name does not match the model/collection name, then pass an object {attr: class} | |
| has_one: | |
| "primary_email_address" : "Email" | |
| "primary_address" : "Address" | |
| #base will handle the parsing and initializing of these in its default functions | |
| #base.js.coffee | |
| initialize: (object) -> | |
| @setup_nested() | |
| parse: (json) -> | |
| @setup_nested(json) | |
| json | |
| #you can iterate through the nested keys by using the following functions: | |
| @models() # -> ['primary_email_address', 'primary_address'] | |
| @collections() # -> ["email_addresses", "addresses", "phone_numbers"] |
| #the base model does some work for you. firstly it binds the backbone url function to be called by default. | |
| #this enables you to use urlRoot in its proper way. rails-backbone messes this up. | |
| #(this rids the need for that url: -> "clients/#{@id}" nonsense | |
| #Base.js.coffee | |
| url: -> Backbone.Model.prototype.url.call @ | |
| #Client.js.coffee | |
| urlRoot: "/clients" |
| #base will validate your nested models and collections by default for you | |
| #if a collection is a BaseCollection then it will return validate on all the models | |
| #in addition you can set presence validations within the model, and they will be called by default | |
| #client.js.coffee | |
| validates_presence_of: ["name"] |