Search code examples
javascriptbackbone.js

my Backbone.View functions are undefined


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/


Solution

  • 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;