0

I am extending Backbone.View and then calling its render function, but I get an "Uncaught TypeError: view.render is not a function"

code (running in document onload):

var view = Backbone.View.extend({
 id: "my-view",
 render: function() {
   console.log("in render, this =", this);
   this.el.innerHTML = "Hello";
   return this;
 }
});
console.log("outside view, view =", view);
document.body.appendChild(view.render().el);

result in console:

outside view, view = function (){return r.apply(this,arguments)}
VM639:58 Uncaught TypeError: view.render is not a function

It looks like it is meant to be a constructor, but I tried making a new view() and then calling its functions and got a different error:

Uncaught TypeError: this._ensureElement is not a function
at e.View (backbone-min.js:1)   

I have looked for the answer to this elsewhere (Backbone View: function is undefined, Render a View of Backbone Model returns undefined), but the samples were complicated and I don't know how to apply the answer to my code. I have made a very simple example and hope that will encourage you to answer it even if my mistake is very basic.

Here is a jsfiddle: https://jsfiddle.net/s9Lhq82a/

Community
  • 1
  • 1
alr3000
  • 83
  • 11

1 Answers1

1

You defined a view class that extends from Backbone.View. To create the instance of that class, you have to use new.

var View = Backbone.View.extend({
    // this is your View Class
});

var myView = new View(); // this is an instance of View, it has a render function
myView.render().el;
Cory Danielson
  • 14,314
  • 3
  • 44
  • 51
  • Thank you, but with that I get an error inside backbone.js: Uncaught TypeError: Right-hand side of 'instanceof' is not an object. [fiddle](https://jsfiddle.net/s9Lhq82a/1/) – alr3000 Jan 19 '17 at 07:13
  • However, though it doesn't work in the fiddle, the change works in my real code, so Yay! – alr3000 Jan 19 '17 at 07:26