出于某种原因,我无法正确地将this
传递给回调以呈现视图。我已经尝试了_.bind和_.bindAll方法,但无论我使用哪种方式传递上下文,我总是在渲染中使用与this
< EM>初始化
感谢任何帮助
Navigation.Collection = Backbone.Collection.extend({
model : Navigation.Model,
comparator : function(item) {
return item.get("orderId");
}
});
Menu = new Navigation.Collection();
Navigation.Views.List = Backbone.View.extend({
el : 'nav',
tagName : "div",
className : "navigation",
collection : Menu,
initialize : function(e) {
console.log(this);
this.template = "navigation/list";
this.settings = Settings;
this.collection.on("add", this.render, this);
},
render: function() {
console.log(this);
var renderedContent = this.template(this.collection.toJSON());
console.log(renderedContent);
return this;
},
绑定示例:
initialize : function(e) {
this.collection.on("add", _.bind(this.render, this));
}
bindAll示例:
initialize : function(e) {
_.bindAll(this, "render");
this.collection.on("add", this.render);
}
首次打印:
child {cid: "view2", options: Object, views: Object, __manager__: Object, _removeViews: function…}
第二次印刷:
Object {resolve: function, resolveWith: function, reject: function, rejectWith: function, notify: function…}
编辑:添加调用'render'的位置。这是在代码中定义Navigation.View.List(如上所示)之后的。
Navigation.registerModule = function(data) {
_.extend(data, {
id : Math.random()
});
Menu.add(new Navigation.Model(data));
Navigation.LayoutManager.removeView(true);
Navigation.cachedRendering = null;
};
Navigation.View = new Navigation.Views.List();
Navigation.LayoutManager = new Backbone.Layout({
views : {
nav : Navigation.View
}
});
Navigation.LayoutManager.$el.appendTo("nav");
Navigation.LayoutManager.render();
return Navigation;
编辑:如果其他人偶然遇到同样的事情,解决方案是使用beforeRender
和afterRender
。之所以出现混乱,是因为我正在升级依赖项,而旧版本的 backbone.layoutmanager 没有这两个帮助程序,而是使用了render()
- 使用manage
参数来访问after
州。
答案 0 :(得分:1)
请尝试以下方法:
this.listenTo(this.collection, "add", this.render);
ListenTo是在0.9.x中添加的,因为“...当你想删除视图时,可以更容易地创建让所有观察者都不受限制的视图。”,引自骨干文档。这里有一个很好的答案,详细介绍了可能有用的上下文:https://stackoverflow.com/a/16824080/486434
答案 1 :(得分:1)
您的视图渲染正在被这行代码调用:
https://github.com/tbranyen/backbone.layoutmanager/blob/master/backbone.layoutmanager.js#L472:
// Render the View into the el property.
if (contents) {
rendered = options.render.call(renderAsync, contents, context);
}
问题在于options.render.call(renderAsync, contents, context);
将this
关键字与renderAsync
绑定,这是一个承诺。
我不熟悉Backbone布局管理器,但看起来原始上下文是作为render
方法的第二个参数传递的。然后,您可以稍微修改渲染方法来使用它。
render: function( contents, context ) {
var self = context ? context : this;
var renderedContent = this.template(self.collection.toJSON());
return this;
},