Andrew
Andrew

Reputation: 238947

Backbone.js and CoffeeScript: How to create an attribute function that can be rendered

I haven't seen this type of thing in any examples that I have come across. I need to create an attribute function that depends on other attributes. For example:

# coffeescript
class Person extends Backbone.Model
  fullName: -> @get('first') + ' ' + @get('last')

class MyView extends Backbone.View
  template: ...
  render: ->
    @$el.html @template(@model.toJSON())

new MyView(new Person(first:'Joe', last:'Moe)

# my template
<span><%= fullName %></span>

In most examples, I see that the model is always converted to JSON before passing to the template, so is there a way to set up the toJSON method to include this fullName attribute? Or should I pass the model to the template instead?

Upvotes: 1

Views: 273

Answers (1)

Paul Hoenecke
Paul Hoenecke

Reputation: 5060

One simple way is to pass a different object to the template function:

modelData =
  data: @model.toJSON()
  fullName: @get('first') + ' ' + @get('last')
@template(modelData)

Then in the template:

<span><%= fullName %></span>
<span><%= data.first %></span>

toJSON is usually more for serialization, so you may not want to change it to output display-only stuff. You could also just pass the model to the template, like you suggest.

Yet another alternative (javascript not coffee...):

toDisplayJSON: function(){
    var json = this.toJSON();
    json.fullName = this.get('first') + ' ' + this.get('last');
    return json;
}

I knew I had read another way of doing this (the view-model approach): Dealing with non-saveable values in Backbone

Upvotes: 1

Related Questions