【问题标题】:Uncaught TypeError: undefined is not a function Backbone TemplateUncaught TypeError: undefined is not a function Backbone Template
【发布时间】:2014-04-29 01:47:13
【问题描述】:

尽管我使用 Underscore 的 _.template() 定义了 @template,但我在 @template 上得到了 Uncaught TypeError: undefined is not a function

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 )
    @

当我执行console.log @template 时,如果在渲染函数中调用,我会得到undefined。当我从initialize 中调用console.log @template 时,我得到了

function (data) {
      return render.call(this, data, _);
    }

【问题讨论】:

    标签: javascript jquery templates backbone.js underscore.js


    【解决方案1】:

    你在调用each时没有指定context参数:

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

    所以当你说@tempate(post.attributes) 时,@ 可能是window。调用each时指定所需的context

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

    或者在回调中使用fat-arrow (=>)

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

    【讨论】:

    • 是的,当我回顾这个问题时,我已经找到了答案。
    猜你喜欢
    • 2011-08-13
    • 1970-01-01
    • 2014-08-15
    • 2015-01-14
    • 2014-07-06
    • 2014-09-01
    • 2015-11-04
    • 2013-03-06
    • 1970-01-01
    相关资源
    最近更新 更多