2011-12-23 86 views
1

意外的是,下面的代碼將打印Test1 undefined而不是Test1 Test2主幹視圖實例化問題

var MyView = Backbone.View.extend({ 
    initialize: function() { 
     console.log(this.collection, this.test); 
    } 
}); 

new MyView({collection: "Test1", test: "Test2"}); 

我在做什麼錯?

回答

4

只有選件參數中的以下屬性纔會合併到視圖屬性中。

模型,收集,薩爾瓦多,ID,屬性,類名,標籤名(See the source code

的其他財產被放置在選項財產的觀點。

所以要從初始化方法訪問測試屬性,您可以按如下方式更新您的代碼。

console.log(this.collection, this.options.test); 
+0

呃,爲什麼!?這似乎是不必要的和不自然的。 – Randomblue 2011-12-23 17:53:53

+1

@Randomblue:曾聽說過封裝?而這種行爲是[記錄的接口](http://documentcloud.github.com/backbone/#View-constructor)的一部分,所以它應該不會令人驚訝。 – 2011-12-23 18:11:15

+0

@ muistooshort:不是。你能指出一個好的文章解釋封裝嗎? – Randomblue 2011-12-23 19:40:59