Cover by Alex MacCaw

Safari, the world’s most comprehensive technology and business learning platform.

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required

O'Reilly logo

Models

If you take a peek at Spine’s source code, you’ll see that the vast majority of it deals with models, and rightly so—models are the central part of any MVC application. Models deal with storing and manipulating your application’s data, and Spine simplifies this by providing a full ORM.

Rather than use the create() function to make a new model, which is already reserved, use Spine.Model.setup(name, attrs), passing in the model name and an array of attribute names:

// Create the Task model.
var Task = Spine.Model.setup("Task", ["name", "done"]);

Use include() and extend() to add instance and class properties:

Task.extend({  
  // Return all done tasks.
  done: function(){ /* ... */ }
});

Task.include({
  // Default name
  name: "Empty...",
  done: false,

  toggle: function(){ 
    this.done = !this.done;
  }
});

When instantiating a record, you can pass an optional object containing the record’s initial properties:

var task = Task.init({name: "Walk the dog"});
assertEqual( task.name, "Walk the dog" );

Setting and retrieving attributes is the same as setting and getting properties on a normal object. In addition, the attributes() function returns an object literal containing all the record’s attributes:

var task = Task.init();
task.name = "Read the paper";
assertEqual( task.attributes(), {name: "Read the paper"} );

Saving new or existing records is as simple as calling the save() function. When saving a record, an ID will be generated if it doesn’t already exist; then, the record will be persisted locally ...

Find the exact information you need to solve a problem on the fly, or go deeper to master the technologies and skills you need to succeed

Start Free Trial

No credit card required