简体   繁体   中英

Backbone Cannot read property 'property' of undefined error in backbone view

I've just decided to learn backbone. I'm following a video tutorial. Everything works fine there, but at my end I get this error "Uncaught TypeError: Cannot read property 'name' of undefined".

Here's my code:

var MenuItemDetails = Backbone.View.extend({
        render: function() {
            var markup = this.options.name + this.options.category + this.options.imagepath;
            // I also had some html markup in the string above, of course, but I've striped it because stackoverflow didn't show it in the preview of my post.
            this.$el.html(markup);
            return this;
        }
    });

    var AppRouter = Backbone.Router.extend({
        routes: {
            "" : "list",
            "menu-items/new" : "itemForm",
            "menu-items/:item" : "itemDetails"
        },

        list: function() {
            $('#app').html('List screen');
        },

        itemDetails: function(item) {
            var view = new MenuItemDetails({ name: item, category: 'Some category', imagepath: 'no-image.jpg' });
            $('#app').html(view.render().el);
        },

        itemForm: function() {
            $('#app').html('New item form');
        }
    });

    var app = new AppRouter();

    $(function() {
        Backbone.history.start();
    });

The "itemDetails" function gives "Uncaught TypeError: Cannot read property 'name' of undefined" error. Of course, if I don't use the 'name' property in the view, I get "Uncaught TypeError: Cannot read property 'category' of undefined". In the video tutorial that I'm following, everything works fine (it uses version 0.9.1 of backbonejs). I use the latest (1.1.0).

Does anybody know why do I get this error? There isn't anything misspelled, everything is in the right order (exactly as in the video tutorial, where it works). Why does backbone throws me this error?

Backbone views used to automatically copy the constructor options to this.options but no longer :

Change Log
1.1.0 — Oct. 10, 2013

  • Backbone Views no longer automatically attach options passed to the constructor as this.options , but you can do it yourself if you prefer.

So if you're depending on this.options being set in your views then you'll have to do it yourself:

var MenuItemDetails = Backbone.View.extend({
    initialize: function(options) {
        this.options = options;
    },
    //...
});

Or better, unpack the options so that you know what your view's interface is:

initialize: function(options) {
    this.options = _(options).pick('name', 'category', 'imagepath');
}

This way you at least have a list of what you're expecting to see in options .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM