将collection.fetch作为命名函数传递给collection.bind不起作用
问题描述:
我有两个Backbone集合。我想绑定到一个重置事件。当该事件被触发,我想打电话给取的第二集合,就像这样:将collection.fetch作为命名函数传递给collection.bind不起作用
App.collections.movies.bind("reset", App.collections.theaters.fetch);
第二取不闪光,但。但是,如果我通过一个匿名函数调用aters.fetch,它可以正常工作:
App.collections.movies.bind("reset", function() { App.collections.theaters.fetch(); });
任何想法为什么会出现这种情况?
继承人我的完整代码。我没有表现出任何模型或集合,因为它是一个大量的代码,但让我知道,如果你认为这可能是问题的根源:
var App = {
init: function() {
App.collections.theaters = new App.Theaters();
App.collections.movies = new App.Movies();
App.events.bind();
App.events.fetch();
},
events: {
bind: function() {
App.collections.theaters.bind("reset", App.theaterManager.assign);
App.collections.movies.bind("reset", function() { App.collections.theaters.fetch(); });
},
fetch: function() {
App.collections.movies.fetch();
}
},
collections: {},
views: {},
theaterManager: {
// Provide each model that requires theaters with the right data
assign: function() {
// Get all theaters associated with each theater
App.theaterManager.addToCollection("theaters");
// Get all theaters associated with each movie
App.theaterManager.addToCollection("movies");
},
// Add theaters to a collection
addToCollection: function (collection) {
App.collections[collection].each(function (item) {
item.theaters = App.theaterManager.getTheaters(item.get(("theaters")));
});
},
// Returns a collection of Theaters models based on a list of ids
getTheaters: function() {
var args;
if (!arguments) {
return [];
}
if (_.isArray(arguments[0])) {
args = arguments[0];
} else {
args = Array.prototype.slice.call(arguments);
}
return new App.Theaters(_.map(args, function (id) {
return App.collections.theaters.get(id);
}));
}
}
};
$(function() {
App.init();
});
答
这一切都与功能方面做。在Javascript中调用函数的方式是一个常见的混淆。
在第一种方式中,您正在处理要调用的函数,但没有定义上下文。这意味着任何人称它会成为“这个”。很可能相当于打电话App.collections.movies.fetch()
这不是你想要的。至少,我猜这就是上下文的内容。很难确定......它可能是jQuery,它可能是Backbone.sync
。要告诉的唯一方法是在Backbone.collections.fetch
函数中放置断点并打印出this
变量。无论如何,这不会是你想要的。
在第二种情况下,您再次将它交给一个函数,但在内部指定调用该函数的上下文。在这种情况下,fetch
以App.collections.theaters
作为上下文被调用。
......那是清楚的吗?
明白了。我需要做的是在绑定事件时传递上下文。骨干允许你这样做:collection.bind(“event”,handle,context) – Adam
好吧,你去!我没有意识到'colleciton.bind'让你有能力传递上下文。赢得! –
我试过传递一些不同的上下文,但都没有工作。我试过这个,它只是窗口对象,App.collections.theaters和App.collections.movies。仍然没有运气。 – Adam