Backbone 和 bindAll:“func 未定义"; [英] Backbone and bindAll: "func is undefined"

查看:25
本文介绍了Backbone 和 bindAll:“func 未定义";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用 bindAll 时遇到了问题.我得到的错误是 func 未定义.对我做错了什么有什么想法吗?

I've got problems using bindAll. The error I get is func is undefined. Any thoughts on what I'm doing wrong?

我都试过了

  • bindAll(因上述错误而失败)和
  • 单独的绑定s(不工作)
  • bindAll (fails with the above error) and
  • individual binds (don't work)
window.test = Backbone.View.extend({

  collection: null

  initialize: ->
    console.log('initialize()')
    console.log(this)
    # _.bindAll(this, ["render", "foo"])
    _.bind(this.render, this) # these don't throw errors, but binding won't work
    _.bind(this.foo, this) 
    @collection = new Backbone.Collection()
    @collection.bind "add",     @render
    @collection.bind "add",     @foo
    @render()

  foo: ->
    # won't be bound to the view when called from the collection
    console.log("foo()")
    console.log(this)
    console.log(this.collection) # undefined (since this is the collection, not the view)

  render: ->
    console.log("render()")
    console.log(this)
    return this

})
testInstance = new window.test();
# using _.bind instead of bindAll we get past this point, however this won't be the view
testInstance.collection.add({})

推荐答案

你使用的是 CoffeeScript,你不需要下划线的绑定.CoffeeScript 内置了它.只需使用胖箭头"

You are using CoffeeScript, you don't need underscore's bind. CoffeeScript has it built in. Just use "fat arrows"

foo: =>
    #Your foo implementation goes here
render: =>
    # your render implementation goes here

在此处搜索胖箭头":http://jashkenas.github.com/coffee-script/

但是,对于 _.bindAll,您不需要将方法名称作为数组提供.您可以执行 _.bindAll(this)_.bindAll(this, 'render', 'foo') (方法名称是 var args,而不是显式列表).看看有没有帮助.

However, with regards to _.bindAll, you don't need to provide the method names as an array. You can do either _.bindAll(this) or _.bindAll(this, 'render', 'foo') (method names are var args, not an explicit list). See if that helps.

这篇关于Backbone 和 bindAll:“func 未定义";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆