2013-12-16 44 views
2

我刚刚决定学习骨干。我正在观看视频教程。一切工作正常,但在我的结尾,我得到这个错误“未捕获TypeError:无法读取未定义的属性'名称'。骨干无法读取骨干视图中未定义错误的属性'属性'

这里是我的代码:

 

    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”功能赋予“遗漏的类型错误:无法未定义的读取属性‘名’”错误。当然,如果我不在视图中使用'name'属性,我会得到“Uncaught TypeError:无法读取未定义的属性'类别'。在我遵循的视频教程中,一切正常(它使用backbonejs的0.9.1版本)。我使用最新的(1.1.0)。

有谁知道我为什么会得到这个错误? 没有任何拼写错误,所有内容都按照正确的顺序排列(正如在视频教程中一样)。骨干为什么会抛出我这个错误?用于自动拷贝构造函数选项

回答

7

骨干意见this.optionsbut 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.

所以,如果你根据this.options在你的观点被设置,那么你必须做你自己:

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

或者更好,解压选项,让你知道你的观点的接口是什么:

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

这样你至少有一个你期望在options中看到的列表。

+1

我喜欢白名单的选项。另一个值得一读的答案:) – nikoshr

+0

@nikoshr:是的,我从来不喜欢自动'this.options'的东西,太多难以追踪的“我该如何在六个月内调试这个远程行为?”对我的口味有魔力。 –