关于javascript:骨干网无法在骨干网视图中读取未定义错误的属性“属性”

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

我刚刚决定学习骨干。 我正在观看视频教程。 那里一切正常,但最后我收到此错误" Uncaught TypeError:无法读取未定义的属性'name'"。

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
    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();
    });

" itemDetails"函数给出"未捕获的TypeError:无法读取未定义的属性'名称'"错误。 当然,如果我在视图中不使用'name'属性,则会收到" Uncaught TypeError:无法读取未定义的属性'category'"。 在我关注的视频教程中,一切正常(它使用的是0.9.1版的ribsjs)。 我使用最新的(1.1.0)。

有人知道为什么我会收到此错误吗?
不会出现任何拼写错误的情况,一切都以正确的顺序进行(就像在视频教程中一样)。 为什么主干向我抛出此错误?


用于自动将构造函数选项复制到this.options的主干视图,但不再:

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.

因此,如果您依赖于在视图中设置的this.options,则必须自己进行操作:

1
2
3
4
5
6
var MenuItemDetails = Backbone.View.extend({
    initialize: function(options) {
        this.options = options;
    },
    //...
});

或者更好地,解压缩选项,以便您知道视图的界面是什么:

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

这样,您至少可以列出希望在options中看到的内容。