How Backbone.JS Handles Models with Computed Attributes

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

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

I also tried to make the attribute a function instead of a value, but Mustache does not get the value when I try to use it.

+6
source share
2 answers

This is how I do it now. I perform calculations when the model is initialized and add a listener to change the model for automatic recounting.

... 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 }, ... 
+3
source

I do not know if I understand the question correctly, but:

Can you pass the actual model to a mustache? for example when rendering

 render: -> rendered_content = @template({model: @model}) $(@.el).html rendered_content @ 

You pass the actual model to the template. Then you have a template

 <td class="quantity"> <input type="text" value="<%= model.get('quantity') %>" name="quantity" /> </td> <td> <%= model.getTotalPrice() %> </td> 

And in the model you declare getTotalPrice ()

 getTotalPrice: -> total_price = @get('price') * @get('quantity') total_price + total_price * @get('tax_rate') 

In fact, I never miss @ model.toJSON in my templates, alawys is the actual model.

0
source

Source: https://habr.com/ru/post/908401/


All Articles