I'm trying to access a model's method from within an .eco template using backbone/marionette.js. I have an Expense
model with a day()
method which, using moment.js, returns '13th'; for example:
class Expense extends Backbone.Model
day: ->
moment.get('date').format('Do')
I can create a new Expense
as follows, and call the day()
method:
coffee = new Expense({name: "Coffee", amount: 2.50, date: "2014-01-13T13:50:00Z"})
coffee.day() # 13th
However, trying to access day()
from within the following view and template is causing me some problems:
class ExpenseView extends Marionette.ItemView
template: "views/_expense"
# views/_expense.jst.eco
<h3 class="expense__name"><%= @name %></h3>
<p class="expense__day"><%= @day() %></p>
I understand why it isn't working...the ItemView
calls serializeData
which returns @model.toJSON()
... therefore, the Expense
's day()
method isn't accessible. Is there an established pattern in the backbone/marionette community that makes model methods available to templates?
So far, I've done the following to make it work:
class ExpenseView extends Marionette.ItemView
template: "views/_expense"
serializeData: ->
_.extend(@model.toJSON(), model: @model)
templateHelpers:
day: ->
@model.day()
But I'm unsure whether this is the best way to go about the problem? Thanks!
transient: true
is a nice addition too! – Posterity