主干:在变量中提供JSON,而不是通过URL获取


Backbone: Feed JSON in a variable instead of fetching through URL

我们正在尝试修改一个现有的脚本,该脚本使用backbone.js从URL中获取JSON,并在屏幕上以定义的方式呈现它。

早些时候,脚本指向一个外部PHP文件以从中获取JSON

url: function () {          
    var ajaxValue = document.getElementById('ajax').value;
    if(ajaxValue==0){
        return this.options.apiBase + '/liveEvents.json';           
    } else {
        var eventDate = document.getElementById('timestamp').value;
        return this.options.apiBase + '/ajax.php?eventDate='+eventDate;         
    }
},

但现在我们正试图省略PHP的要求,纯粹使用Javascript来获得JSON。为此,我们创建了一个JS函数fetch_data_set(),它返回正确的JSON

var ArrayMerge = array1.concat(array2,array3,array4);
return JSON.stringify(ArrayMerge);

所以我们的问题是,我们如何将这个JSON馈送到主干网,而不是使用外部URL。因为如果我们这样做(这显然是错误的):

 url: function () {         
    var ajaxValue = document.getElementById('ajax').value;
    if(ajaxValue==0){           
        var data_set = fetch_data_set();
        return data_set;
    } 
},

它抛出错误:错误:必须指定"url"属性或函数

主要的关键是扩展Backbone.sync而不是url()方法,因此您可以使用这种方式在任何类型的模型中获取模型,并且您可以执行类似的操作,如以下链接:

https://github.com/huffingtonpost/backbone-fixtures/blob/master/backbone-fixtures.js

Backbone.Model包含一个能够从url加载JSON数据的sync()函数。sync()使用url()函数来确定它应该从哪里获取数据。(注:sync()save()fetch()destroy()在引擎盖下调用)

这里的技巧是,您应该停止重写url(),而是直接重新实现sync()。http://backbonejs.org/#Model-同步

这里有一个例子:

// specialized version to be used with a store.js - like object
sync: function(method, model, options) {
  console.log("sync_to_store begin('"+method+"',...) called with ", arguments);
  var when_deferred = when.defer();
  var id = this.url();
  if(method === "read") {
    if(typeof id === 'undefined')
      throw new Error("can't fetch without id !");
    var data = model.store_.get(id);
    // apply fetched data
    model.set(data);
    when_deferred.resolve( [model, undefined, options] );
  }
  else if(method === "create") {
    // use Backbone id as server id
    model.id = model.cid;
    model.store_.set(id, model.attributes);
    when_deferred.resolve( [model, undefined, options] );
  }
  else if(method === "update") {
    if(typeof id === 'undefined')
      throw new Error("can't update without id !");
    model.store_.set(id, model.attributes);
    when_deferred.resolve( [model, undefined, options] );
  }
  else if(method === "delete") {
    if(typeof id === 'undefined')
      throw new Error("can't delete without id !");
    model.store_.set(id, undefined);
    model.id = undefined;
    when_deferred.resolve( [model, undefined, options] );
  }
  else {
    // WAT ?
  }
  console.log("sync_to_store end - Current changes = ", model.changed_attributes());
  return when_deferred.promise;
}
  • 注1:API与香草Backbone略有不同,因为我返回当承诺
  • 注2:url()仍被用作id