Javascript 主干网和bindAll:“;func未定义;

Javascript 主干网和bindAll:“;func未定义;,javascript,binding,backbone.js,coffeescript,underscore.js,Javascript,Binding,Backbone.js,Coffeescript,Underscore.js,我在使用bindAll时遇到问题。我得到的错误是func未定义。有没有想过我做错了什么 我两个都试过了 bindAll(因上述错误而失败)和 单个binds(不工作) window.test=Backbone.View.extend({ 集合:空 初始化:-> console.log('initialize()') console.log(这个) #bindAll(这个,[“render”,“foo”]) _.bind(this.render,this)#这些不会抛出错误,但绑定不起作用 _

我在使用bindAll时遇到问题。我得到的错误是
func未定义
。有没有想过我做错了什么

我两个都试过了

  • bindAll
    (因上述错误而失败)和
  • 单个
    bind
    s(不工作)
window.test=Backbone.View.extend({
集合:空
初始化:->
console.log('initialize()')
console.log(这个)
#bindAll(这个,[“render”,“foo”])
_.bind(this.render,this)#这些不会抛出错误,但绑定不起作用
_.bind(this.foo,this)
@collection=新主干。collection()
@collection.bind“添加”,@render
@collection.bind“添加”,@foo
@render()
傅:->
#从集合调用时不会绑定到视图
console.log(“foo()”)
console.log(这个)
console.log(this.collection)#未定义(因为这是集合,而不是视图)
渲染:->
log(“render()”)
console.log(这个)
还这个
})
testInstance=新窗口。test();
#使用u.bind而不是bindAll,我们就可以越过这一点,但是这不是我们的观点
testInstance.collection.add({})

您使用的是CoffeeScript,不需要下划线绑定。咖啡脚本内置了它。只要用“肥箭”

在此处搜索“胖箭头”:


但是,对于
\uuu.bindAll
,您不需要将方法名作为数组提供。您可以执行
.bindAll(this)
.bindAll(this,'render','foo')
(方法名称是变量参数,而不是显式列表)。看看这是否有帮助。

彼得·莱昂斯在这两方面都是正确的。您希望将每个函数作为参数传递给bindAll,而不是传递函数数组。当使用coffeescript时,胖箭头是一种很棒的方式,可以将函数绑定到定义它的上下文中

我想回答为什么u.bind不为你工作(因为我花了很长时间才弄明白)。答案是u.bind不会改变传递的函数,它会使用提供的参数创建一个新函数。它的标签应该更合适
createBoundFunction
。因此,在您的示例中,让u0.bind起作用就是:

this.render = _.bind(this.render, this)
this.foo = _.bind(this.foo, this) 
此外,在浏览源代码时,我学到了很多关于函数如何绑定的知识,所以我希望您不要介意对函数绑定的离题,从coffee脚本的功能开始

var __bind = function(fn, me){ return function(){return fn.apply(me, arguments); }; }
CoffeeScript将上述函数插入到使用fat箭头(=>)的每个文件中。这是老办法。它创建并返回一个新函数,该函数调用您的函数并应用您传递的上下文和参数。CoffeeScript然后生成构造函数,并为每个fat arrow定义的函数调用_绑定。对于Peter Lyon的解决方案,生成的代码如下所示:

this.render = __bind(this.render, this)
this.foo = __bind(this.foo, this) 
this.render = this.render.bind(this)
this.foo = this.foo.bind(this)
在我当前的项目中,我有9个使用胖箭头的视图,因此我定义了9次绑定,这似乎违反了DRY,但谁在乎,它是为我生成的

ECMAScript 5禁止在函数原型上使用新方法

 Function.prototype.bind(thisArg [, arg1[, arg2[, ...]]])
此方法将使您的代码看起来像这样:

this.render = __bind(this.render, this)
this.foo = __bind(this.foo, this) 
this.render = this.render.bind(this)
this.foo = this.foo.bind(this)
不需要外部库或生成的方法。问题是,这只在最新的+最好的浏览器(FF4、IE9、CH10>)中受支持,因此在几年内不可能完全使用它

下划线结合了这两个概念:

_.bind = function(func, obj) {
  if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func,   slice.call(arguments, 1));
  var args = slice.call(arguments, 2);
  return function() {
    return func.apply(obj, args.concat(slice.call(arguments)));
  };
};
其中nativeBind等于Function.prototype.bind。因此,下划线检查新ECMA5绑定方法的可用性,如果不存在,则创建一个匿名函数,用您选择的上下文调用您的函数


如果我知道或者能够找到Function.prototype.bind所赋予的某些优势的信息,我想说的是避免使用CS-fat箭头,而使用uz.bind,特别是对于那些已经在库中包含下划线的主干项目,但我不知道它是否赋予优势,所以这可能不重要

主干网现在允许您添加一个附加参数,以将
绑定到回调。看见这样,视图的方法将绑定到视图,而不是集合。

尚未成功使fat箭头在主干模型“方法”上起作用。你是对的,我的bindAll语法错了。谢谢