Defining Models

In notebook:
FrontEndMasters BackboneJS
Created at:
2016-06-09
Updated:
2016-06-09
Tags:
libraries JavaScript
“Backbone Models organises an object’s attributes.”

To define a model:
  var Song = Backbone.Model.extend({
  initialize: function () {
    console.log("you've initialised the song model")
  }
});

var songModel = new Song();
You can create a generic Backbone model just by calling ​var myModel = new Backbone.model​To use the model:
  var songModel = new Song({
  artist: "Death Cab for Cutie",
  title: "Codes & Keys"
});

songModel.get('artist'); 
// "Death Cab for Cutie"

Accessing model attributes

​.get(‘attribute_name’)
or even directly, but not recommended:
​songModel.attributes.artist

​songModel.toJSON();​ returns JSON representation

Setting model attributes

​songModel.set({artist: “Ben Gibbard”});
​set​ works with one or two arguments
Default values
Setting default values with two strategies. Either on ​extend​ing the model (A) or on initialisation (B).
  // A

var Song = Backbone.Model.extend({
  defaults: {
    title: "Codes & Keys",
    // ..
  }
})

// B

var Song = Backbone.Model.extend({
  initialize: function () {
    this.set({
      title: "Codes & Keys",
      //..
    })
  }
});
Talks about primitive values being copied (in memory) vs objects passed as reference.

So this can create bugs, since all newly created objects will share the same ​default​ object and can override it.

“B” will also trigger a change event.

Listening for changes

  var Song = Backbone.Model.extend({
  initialize: function () {
    this.on('change', function(){
      // call methods when any attribute changes
    });
    this.on('change:artist', function(){
      // when 'artist' attribute changes
    })
  }
});
You can also listen to several events by ​.on(‘change update set’..)​ a space delimited list.

Persisting models

Save model changes to the server by calling ​.save()​ on a model instance. ​.set()​ saves in-memory only.

Models can have a ​url​ property or an url ​root​. An url ​root​ will try to dynamically get use the id property on the model (follows REST conventions).

​songModel.save()​ Push this data to the server
​songModel.fetch()​ Overwrite this instance with newer data from the server
​songModel.destroy()​ Destroy the model on the server (sends ​DELETE​ to the server) it will NOT remove references to the model (except in a collection)