2011-12-23 50 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