Pregunta

I'm getting Uncaught TypeError: undefined is not a function on my @template even though I defined @template using Underscore's _.template()

IntroProject.Views.Posts ||= {}

class IntroProject.Views.Posts.IndexView extends Backbone.View

  el: '#posts'

  template: _.template( $('#home-post-template').html() ) if $('#home-post-template').length

  initialize: ->
    @collection.bind "reset", ->
      @render()
    , @

  render: ->
    @collection.each (post) ->
      console.log @template( post.attributes )
    @

when I do console.log @template I get undefined if called in the render function. When I call console.log @template from within the initialize even, I get

function (data) {
      return render.call(this, data, _);
    }
¿Fue útil?

Solución

You haven't specified the context argument when calling each:

@collection.each (post) ->
  console.log @template( post.attributes )

so @ is probably window when you say @tempate(post.attributes). Specify the desired context when calling each:

@collection.each (post) ->
  console.log @template(post.attributes)
, @

or use a fat-arrow (=>) with the callback:

@collection.each (post) =>
  console.log @template(post.attributes)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top