在 Backbone.js 和 Underscore.js 中绑定回调
我有以下代码:
initialize: function() {
_.bindAll(this);
var callBack = function(res) {
window.item = new Item(res);
this.render();
};
_.bind(callBack, this);
$.get('/item/parse', {
uri: decodeURIComponent($.urlParam('uri')),
title: decodeURIComponent($.urlParam('title'))
},
callBack
);
},
目的是在 $.get 函数完成后调用 render() 。但是,即使在使用 _.bind 绑定回调函数之后,我仍然在控制台中收到“Object has no function render”。我在这里使用绑定不正确吗?
I have the following code:
initialize: function() {
_.bindAll(this);
var callBack = function(res) {
window.item = new Item(res);
this.render();
};
_.bind(callBack, this);
$.get('/item/parse', {
uri: decodeURIComponent($.urlParam('uri')),
title: decodeURIComponent($.urlParam('title'))
},
callBack
);
},
The intention is that render() should be called after the $.get function finishes. However, even after binding the callback function with _.bind, I still get "Object has no function render" in the console. Am I using bind incorrectly here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
_.bind
返回一个新函数,因此:您也可以使用
_.bindAll
,但您必须在定义函数之后调用它。否则,在调用_.bindAll
时不会有任何函数。请注意,在这种情况下,您必须使用this.callBack = ...
,否则this
将不会包含任何函数。同时使用
_.bind
和_.bindAll
是多余的。_.bind
returns a new function, so:You can also use
_.bindAll
, but you have to call it after you define the function. Otherwise there are no functions at the time you call_.bindAll
. Note that you have to usethis.callBack = ...
in that case, because otherwisethis
won't consist of any functions.Using both
_.bind
and_.bindAll
is superfluous.我通常在模型上编写一个“加载”方法,并提供回调作为参数。然后我从视图中的 render() 方法调用此方法,并在回调函数中执行我需要执行的操作(当然,该回调是在数据加载后在模型中触发的)。
I usually write a 'load' method on my model which I giva a callback as parameter. Then I call this method from the render() method in the view and do whatever I need to do in the callback function (of course, that callback is triggered in the model after the data has been loaded).