2013-12-16 42 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'的東西,太多難以追蹤的「我該如何在六個月內調試這個遠程行爲?」對我的口味有魔力。 –