我是Backbone.js的新手,我有一个数据集,分配给查看,但我无法获取数据,而我控制台,任何人告诉我我的代码有什么问题?
代码:
var model = Backbone.Model.extend({
data:[
{text:'Google',href:"http://www.google.com"},
{text:'Yahoo',href:"http://www.yahoo.com"},
{text:'Bing',href:"http://www.bing.com"}
]
});
var View = Backbone.View.extend({
initialize:function(){
this.render();
},
render:function(){
var data = this.model.get('data');
console.log(data);
}
});
var myView = new View({model:model});
我得到的错误在这里:
TypeError: this.model.get is not a function
[Break On This Error]
var data = this.model.get('data');
答案 0 :(得分:3)
您需要实际实例化模型;使用extend
只会创建Backbone.Model
原型的扩展名。 The following creates a new instance of Backbone.Model
,并使用数据初始化它:
var model = new Backbone.Model({
data:[
{text:'Google',href:"http://www.google.com"},
{text:'Yahoo',href:"http://www.yahoo.com"},
{text:'Bing',href:"http://www.bing.com"}
]
});
var myView = new View({ model: model });
如果您想将数据放入模型本身的类型中,那么您可以使用defaults
属性:
var Model = Backbone.Model.extend({
defaults: {
data:[
{text:'Google',href:"http://www.google.com"},
{text:'Yahoo',href:"http://www.yahoo.com"},
{text:'Bing',href:"http://www.bing.com"}
]
}
});
var model = new Model();
var myView = new View({ model: model });