BackboneJS : where to declare the function inside

2019-03-04 03:50发布

问题:

I'm starting to learn BackboneJS. Here is my code :

var TodoItem = Backbone.Model.extend({});

var todoItem = new TodoItem({
    description: 'Pick up milk',
    status: 'incomplete',
    id: 1
});

var TodoView = Backbone.View.extend({
    render: function()
    {
        var html = '<h3>' + this.model.get('description') + '</h3>';
        $(this.el).html(html);
    }
});

var todoView = new TodoView({ model: todoItem });
todoView.render();
console.log(todoView.el);

But I get this error :

Uncaught TypeError: Expecting a function in instanceof check, but got undefined
    _.extend._setElement @ backbone.js:1233
    _.extend.setElement @ backbone.js:1222
    _.extend._ensureElement @ backbone.js:1302
    Backbone.View @ backbone.js:1170
    child @ backbone.js:1831
    (anonymous function) @ (index):28

What am I doing wrongly ? I don't really understand where I need to create the function it's waiting for.

回答1:

In backbone.js, _setElement is used to set the this.$el and this.el. Your particular error is happening on the first line in the following Backbone.js code:

 _setElement: function(el) {
   this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
   this.el = this.$el[0];
 },

As you can see, we are checking if it's an instanceof Backbone.$, but based on your error Backbone.$ is null. This error is indicating that jQuery either didn't load or isn't on the page. Make sure you include jQuery before you include Backbone on your page.

Here's an example of the needed requires using some CDNs that host these libraries.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.1/backbone-min.js"></script>