For some reason, I can't get this
to correctly be passed to the callback to render the view. I've tried _.bind and _.bindAll methods, but no matter which way I use to pass context, I always end up with a different this
in render than I had in initialize
Any help is appreciated
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;
},
Example with bind:
initialize : function(e) {
this.collection.on("add", _.bind(this.render, this));
}
Example with bindAll:
initialize : function(e) {
_.bindAll(this, "render");
this.collection.on("add", this.render);
}
Console output
First print:
child {cid: "view2", options: Object, views: Object, __manager__: Object, _removeViews: function…}
Second print:
Object {resolve: function, resolveWith: function, reject: function, rejectWith: function, notify: function…}
EDIT: Adding where 'render' is called. This is immediately after Navigation.View.List(seen above) is defined in the code.
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;
EDIT: In case anyone else stumbles across the same thing, the solution is to use beforeRender
and afterRender
. The confusion happened because I was upgrading dependencies and the old version of backbone.layoutmanager did not have these two helpers, and render()
was used instead - with a manage
parameter to access the after
state.