Backbone - get方法不返回输出

时间:2012-12-15 09:58:33

标签: backbone.js underscore.js

我是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');

1 个答案:

答案 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 });