O'Reilly logo

JavaScript Web Applications by Alex MacCaw

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required