1

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?

Andrew
  • 227,796
  • 193
  • 515
  • 708

1 Answers1

1

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

Community
  • 1
  • 1
Paul Hoenecke
  • 5,060
  • 1
  • 20
  • 20
  • That's a good point. Though, I would probably keep the logic in my model: `fullname: @model.fullName()` – Andrew Mar 04 '13 at 21:19