javascript - 未捕获的类型错误 : undefined is not a function Backbone Template

标签 javascript jquery templates backbone.js underscore.js

即使我使用 Underscore 的 定义了 @template,我的 @template 上仍然收到 Uncaught TypeError: undefined is not a function >_.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 )
    @

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

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

最佳答案

调用 each 时您尚未指定 context 参数:

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

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

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

或使用 fat-arrow (=>)使用回调:

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

关于javascript - 未捕获的类型错误 : undefined is not a function Backbone Template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23354114/

相关文章:

javascript - 从元素中取消附加 jQuery 函数

javascript - 如何在 anchor 标记 <a href> 中打开警告框?

php - PHP cookies和 'JS' cookies是一样的吗?

javascript - 在 Firefox 中打印 PDF

jquery - 将 Draggable 连接到 Sortable 会导致辅助元素跳转

c++ - 是否可以有相互引用的 C++ 模板?

templates - Julia 函数签名和子类型,特别是 String、ByteString

javascript - 如何使使用 replaceWith 添加的 html 的单选按钮的更改事件起作用

javascript - 如何使用 Javascript 转换字符编码? jQuery

templates - Go Template ParseFiles 函数解析多个文件