Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to use defaults vs the initialize constructor on a model

Tags:

backbone.js

So, I'm trying to learn how to use Backbone and I keep switching back and forth between using the defaults object and the initialize method. If I use the method, it's with "this.set()" to set attributes, etc. Otherwise those attributes are set in the default object.

I've looked around on google and I can't seem to find a recommended way or "common" pattern of when to use defaults or when to use initialize. I can make my code work both ways and both yield an object with the desired attributes, but it bugs me because i'm unsure if i'm using it incorrectly.

like image 398
Sneaky Wombat Avatar asked Dec 08 '11 16:12

Sneaky Wombat


1 Answers

You would use the defaults object for all "static" data as you can only define them once for a model class. You will need the initialize method if you have to add dynamic per instance properties. For example:

initialize: function() {
  this.set({displayName: this.get('firstname') + this.get('lastname')});
}
like image 143
ProTom Avatar answered Sep 21 '22 05:09

ProTom