0

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

1 回答 1

3

您需要实际实例化模型;usingextend只是创建Backbone.Model原型的扩展。 以下创建 的新实例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 });
于 2012-12-15T10:05:56.727 回答