Backbone toJSON无法渲染

时间:2014-03-03 18:18:25

标签: json backbone.js model render

我是Backbone.js的完整n00b,并且只使用了几天。我正在尝试获取JSON数据以填充模型,在这种情况下,我需要生成两个模型。以下是我一直在使用的示例JSON:

JSON

{
"status": "200",
"total": "2",
    "items":
    [{
        "id": "1",
        "name": "Here is another name",
        "label": "Label for test",
        "description": "A description for more information.",
        "dataAdded": "123456789",
        "lastModified": "987654321"
    },
    {
        "id": "2",
        "name": "Name of item",
        "label": "Test Label",
        "description": "This is just a long description.",
        "dataAdded": "147258369",
        "lastModified": "963852741"
    }]
}

Backbone JS

// MODEL
var Service = Backbone.Model.extend({
defaults: {
    id: '',
    name: '',
    label: '',
    description: '',
    dateAdded: '',
    dateModified: ''
}
});
var service = new Service();

// COLLECTION
var ServiceList = Backbone.Collection.extend({
    model: Service,
    url: "./api/service.php",
    parse: function(response) {
        return response.items;
    }
});
//
var serviceList = new ServiceList();
var jqXHR = serviceList.fetch({
    success: function() {
        console.log("Working!");
                console.log(serviceList.length);
    },
    error: function() {
        console.log("Failed to fetch!");
    }
});


// VIEW for each Model
var ServiceView = Backbone.View.extend({
    el: $('.widget-content'),
    tagName: 'div',
    template: _.template($('#service-template').html()),
    initialize: function() {
        this.collection.bind("reset", this.render, this);
    },
    render: function() {
        console.log(this.collection);
        this.$el.html('');
        var self = this;
        this.collection.each(function(model) {
            self.$el.append(self.template(model.toJSON()));
        });
        return this;
    }
});
//
var serviceView = new ServiceView({
    collection: serviceList
});
console.log(serviceView.render().el);

HTML

<div class="widget-content">
    <!-- Template -->
    <script type="text/template" id="service-template">
        <div><%= name %></div>
    </script>
</div>

当我在控制台登录serviceList.length时,我得到值2,所以我相信JSON对象已成功获取。我也得到了“工作!”对成功的回应。但是,在视图中我显示了一个空对象,它给了我一个空模型。

我仍然在努力了解这样做的最佳方法。也许我应该为“items”使用集合,然后在每个模型数据的集合上进行映射?我究竟做错了什么?非常感谢任何建议或帮助。

2 个答案:

答案 0 :(得分:1)

我可以看到两个问题。首先,您要删除serviceList.reset(list)。您应该通过致电fetch自动填充您的收藏集。 (在任何情况下,fetch的返回值不是服务器的数据结果,而是“jqXHR”对象。

var serviceList = new ServiceList();
var jqXHR = serviceList.fetch({
    success: function(collection, response) {
        console.log("Working!");

        // this is the asynchronous callback, where "serviceList" should have data
        console.log(serviceList.length);
        console.log("Collection populated: " + JSON.stringify(collection.toJSON()));
    },
    error: function() {
        console.log("Failed to fetch!");
    }
});
// here, "serviceList" will not be populated yet

其次,您可能希望将serviceList实例作为其“集合”传递到视图中。实际上,您将空模型实例传递到视图中。

var serviceView = new ServiceView({
    collection: serviceList
});

对于视图,使用集合进行渲染:

var ServiceView = Backbone.View.extend({
    // ...

    initialize: function() {
        // render when the collection is reset
        this.collection.bind("reset", this.render, this);
    },
    render: function() {
        console.log("Collection rendering: " + JSON.stringify(this.collection.toJSON()));

        // start by clearing the view
        this.$el.html('');            

        // loop through the collection and render each model
        var self = this;
        this.collection.each(function(model) {
            self.$el.append(self.template(model.toJSON()));
        });
        return this;
    }
});

Here's一个小提琴演示。

答案 1 :(得分:0)

调用serviceList.fetch是异步调用的,所以当你尝试console.log(serviceList.length);时,服务器还没有发送它的响应,这就是你得到值1的原因,试试这个:

var list = serviceList.fetch({
    success: function() {
        console.log(serviceList.length);
        console.log("Working!");
    },
    error: function() {
        console.log("Failed to fetch!");
    }
});
相关问题