Backbone:没有数据添加到fetch()上的模型

时间:2011-09-09 06:52:23

标签: javascript codeigniter backbone.js

当我尝试从服务器获取数据到我的Backbone模型时,我遇到了问题。你从JSON得到了来自服务器的响应,我觉得它的格式正确。你能看到它有什么问题吗?它看起来像:

[{"id":"1","name":"Fawad Hassan","email":"fawad@test.com"},{"id":"2","name":"Bill 
Gates","email":"bill@test.com"},{"id":"3","name":"Steve 
Jobs","email":"steve@test.com"},{"id":"4","name":"Naveed 
Ahmad","email":"naveed@test.com"},{"id":"5","name":"Mr Zee","email":"zee@test.com"}]

我的Backbone项目代码看起来像这样,我也找不到问题。

window.AppModel = Backbone.Model.extend({
    url: function() {
        return 'http://dev.local/ci/index.php/site/userpost';
    }
});

window.AppContr = Backbone.Collection.extend({
    model: AppModel,
    initialize: function() {
        this.model = new AppModel;
    }
});

window.App = new AppContr({name: "Markus"});

window.AppView = Backbone.View.extend({
    el: $("#content"),
    initialize: function() {
        this.render();
    },
    render: function() {
        console.log(App.model.toJSON());
    }
});

App.model.fetch();
window.View = new AppView;

1 个答案:

答案 0 :(得分:8)

您正在对模型执行fetch,但会在响应中返回Collection。这是主要问题。

第二个问题是你在AppView上调用render是完全随机的,即它与modelcollection没有任何关系。也许在渲染视图时model中没有任何内容。您应该使用collection将呈现绑定到modelbind。每当您致电fetch时,您的视图都会重新渲染,这是Backbone的主要优势之一:)

代码如下:)

window.Person = Backbone.Model.extend({});

window.Addressbook = Backbone.Collection.extend({
    url: 'http://dev.local/ci/index.php/site/userpost',// declare url in collection
    model: Person
}

window.Addresses = new AddressBook();

window.AppView = Backbone.View.extend({
    el: $('#content'),
    initialize: function() {
        Addresses.bind('reset', this.render); // bind rendering to Addresses.fetch()
    },
    render: function(){
        console.log(Addresses.toJSON());
    }
});

window.appview = new AppView();
Addresses.fetch();