I am learning Backbone and JavaScript. I am stuck at one error and this error might be related to pure JavaScript and not Backbone.
While going through tutorial of Backbone (does not uses requireJS), I found below line of code.
var FirstSubViewModel = Backbone.View.extend({
render: function() {
var source = $("#vehicleTemplate").html();
var template = _.template(source);
this.$el.html(template(this.model.toJSON()));
this.$el.attr("data-color", this.model.get("color"));
return this;
},
});
We can clearly see that code returns this, and everything works fine.
Now I am trying to do the same in my own code base (I have used require.JS.
My view Model: With Error: Not Working
define(['backbone'], function(Backbone) {
var FirstSubViewModel = Backbone.View.extend({
template: _.template($('#myChart-template').html()),
render: function() {
$(this.el).html(this.template());
var ctx = $(this.el).find('#lineChart')[0];
return this;
},
initialize: function() {
this.render();
}
});
});
My Controller:
define(['backbone', 'FirstSubViewModel'], function(Backbone, FirstSubViewModel)
{ var ch = new dashboardModel.chart({});
new FirstSubViewModel({
^^ HERE I GET ERROR
el: '#chartAnchor1',
model: ch
});
});
My view Model: Working Totally Fine
define(['backbone'], function(Backbone) {
var FirstSubViewModel = Backbone.View.extend({
template: _.template($('#myChart-template').html()),
render: function() {
$(this.el).html(this.template());
var ctx = $(this.el).find('#lineChart')[0];
// return this; Commented Out!**
},
initialize: function() {
this.render();
}
});
return FirstSubViewModel;
});
Everything works fine if I use return FirstSubViewModel at the bottom rather than having return this in the render function . But I want to try return this in the render function and want everything to work. I don’t want to do return FirstSubViewModel in the end.
Error when used “return this” in the render function:
FirstSubViewModel is not a constructor
Advertisement
Answer
Last return defines what will be included in other modules and in this case is required. Without this this module return undefined.
Lets try in console:
x = undefined new x()
TypeError: x is not a constructor
return FirstSubViewModel is mandatory. return this in render function is recommended.
Code:
define(['backbone'], function (Backbone) {
var FirstSubViewModel = Backbone.View.extend({
template: _.template($('#myChart-template').html()),
render: function () {
console.log("inside first sub view render");
$(this.el).html(this.template());
var ctx = $(this.el).find('#lineChart')[0];
return this;
},
initialize: function () {
this.render();
}
});
return FirstSubViewModel; // Works as expected.
});