Backbone.js:使用Ajax将数据绑定到Collection?

Ric*_*ard 3 javascript ajax backbone.js

我刚开始使用Backbone.js.我想创建一个Collection并从外部源添加一些数据.

实际上数据当前是CSV格式,而不是JSON格式,但是如果要容易的话,我可以用JSON重新渲染它.

那么,有两个问题:

  1. 我在哪里将外部数据绑定到集合?它抱怨如果我没有指定url属性,但我没有真正考虑到URL - 我计划通过Ajax绑定数据.
  2. 我应该使用JSON而不是CSV重新呈现数据,并使用Collection的url属性加载它吗?

我只是尝试将数据直接加载到Collection中,而不是通过url属性:

var Cat = Backbone.Model.extend({});
var CatCollection = Backbone.Collection.extend({
    model: Cat
});
var ajaxData = { 'breed' : 'persian' } // simple example of external data
var catCollection = new CatCollection(ajaxData);
catCollection.fetch();
Run Code Online (Sandbox Code Playgroud)

但是这给出了一个错误:Uncaught Error: A "url" property or function must be specified.

nik*_*shr 7

使用在别处创建的数组初始化/重置集合,而不使用集合的fetch方法

var ajaxData = [{ 'breed' : 'persian' }]; // Backbone.Collection expects an array
var catCollection = new CatCollection(ajaxData);
// catCollection.fetch(); fetch will try to update the data from the server
Run Code Online (Sandbox Code Playgroud)

或使用内置的url/parse来构建模型

var CatCollection = Backbone.Collection.extend({
    model: Cat,
    url: "your ajax source",
    parse: function (csv) {
        //convert your csv in an array of objects
        return csvtoarray;
    },
    fetch: function (options) {
        options = options || {};
        options.dataType = "text";
        return Backbone.Collection.prototype.fetch.call(this, options);
    }
});
var catCollection = new CatCollection();
catCollection.fetch();
Run Code Online (Sandbox Code Playgroud)

将数据服务器端转换为JSON可能比尝试在JS中编写CSV解析器更容易.