n0minal
n0minal

Reputation: 3223

Have one attribute passed to another attribute on the same Backbone model

I have a Backbone model named Summary which has attributes Total and DisplayTotal. What I would like to do is simply duplicate the value of Total and pass it to DisplayTotal.

Also is it possible to set a default for DisplayTotal?

defaults:{
    "DisplayTotal" : this.Total,
}

If possible, as soon as the Total attribute is set, it should set its value to DisplayTotal too.

Upvotes: 0

Views: 39

Answers (1)

fguillen
fguillen

Reputation: 38792

A few things are against this approach.

P.1. defaults is interpreted in Class definition time

So this shouldn't be what you expect, probably this would be window or something like this.

P.2. Backbone attributes are accessed through the Model.get() function

So your example is not correct it should be something like:

defaults:{
  "DisplayTotal" : this.get( "Total" ),
}

But point P.1. is still making this to not work.

You have also a list of approaches to achieve want you want:

S.1. Initialize DisplayTotal in Model.initialize()

initialize: function(){
  this.set( "DisplayTotal", this.get( "Total" ) );
}

S.2. Delay the DisplayTotal initialization to run time

defaults:{
  "DisplayTotal" : function() { return this.get( "Total" ) }
}

Very danger solution, and probably you would have context problems with that this.

S.3. Update DisplayTotal anytime Total is updated

initialize: function(){
  this.on( "change:Total", this.setDisplayTotal, this );
},

setDisplayTotal: function(){
  this.set( "DisplayTotal", this.get( "Total" ) );
}

But I'm affraid you should combine this one with the S.1. due I don't think the event change is triggered in the first set of the attributes.

Upvotes: 1

Related Questions