Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Backbone.JS handle models with calculated attributes

I'm using Backbone.JS with Mustache, so to render my tempaltes I call MyModel.toJSON(). This leaves me with only access to attributes. How can I have some attributes that are always calculated?

I looked at the Backbone.JS documentation and it might work to override validate() but this seems like a hack and may lead to infinite loops.

I also tried making an attribute be a function instead of a value, but Mustache doesn't get a value when I try to use it.

like image 979
Asa Ayers Avatar asked Feb 14 '12 05:02

Asa Ayers


People also ask

How can we get the attribute value of a model in Backbone JS?

js Get model is used to get the value of an attribute on a model. Syntax: model. get(attribute)

How does Backbone JS work?

Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

What is backbone JS model?

Model contains dynamic data and its logic. It performs various types of action on the data like validation, conversion, computed properties, access control etc. 1. It extends Backbone.

Is Backbone JS frontend or backend?

Backend Synchronization BackboneJS is use with the front-end and back-end systems, allows the synchronization with the backend to provide support to RESTful APIs.


1 Answers

This is how I'm currently doing it. I do the calculations when initializing a model, and adding a listener for changes to the model to recalculate automatically.

...
initialize: function() {
  console.log('Lead:initialize');
  _.bindAll(this, 'validate', 'calculate');
  this.bind('change', this.setCalculations, this);
  this.setCalculations();
},
setCalculations: function() {
  this.set({ calculations: this.calculate() }, { silent: true });
},
calculate: function() {
  // do the calculations and return
},
...
like image 163
abraham Avatar answered Nov 15 '22 10:11

abraham