【问题标题】:How to convert a Backbone Collection into an Ampersand one?如何将主干集合转换为与符号集合?
【发布时间】:2015-10-14 10:43:20
【问题描述】:

我正在尝试将 Backbone 集合转换为 & 符号集合。这是我到目前为止所拥有的(我也在使用 CommonJS 从 requirejs 转换为 webpack): 骨干集合:

define([ 'backbone', 'models/loneItem'], function( Backbone, LoneItem ) {
  return Backbone.Collection.extend({
    model: LoneItem,
    urlRoot: '/deeply/nested/path/',
    url: function() {
      return this.urlRoot + this.options.id + '/';
    },
    initialize: function(models, options) {
      this.options = options || {};
    },
    parse: function(response){
      return response.arrayAttribute;
    }
  });
});

然后在视图中我会像这样实例化它:

...
var myCollection = new GroupOfItems( [], { id: 'someID' } );
myCollection.fetch();

然后调用/deeply/nested/path/someID/,在返回的数据中找到arrayAttribute,并将其内容转换为一组LoneItem模型,myCollection可以访问。

对于 & 集合:

var Collection = require('ampersand-rest-collection');
var LoneItem = require('../models/LoneItem');

module.exports = Collection.extend({
  model: LoneItem,
  url: '/deeply/nested/path/',
  parse: function(response){
    return response.arrayAttribute;
  }
});

及其观点:

...
var myCollection = new GroupOfItems();
myCollection.fetchById('someID');

返回的数据是这样的

{
  "arrayAttribute": [
    {"id": "stringID1", "title": "Title A"},
    {"id": "stringID2", "title": "Title B"}
  ]
}

它产生了一个成功的 XHR,但 myCollection 仅成为一个具有单个成员的集合对象,该成员具有来自 LoneItem 的默认道具。返回的数据是否在响应的根级别上没有设置id 属性?或者我缺少的 Backbone 和 Ampersand 集合实现之间有什么区别?

【问题讨论】:

    标签: backbone.js ampersand.js ampersand-collection


    【解决方案1】:

    事实证明,我不应该偏离我原来的实现这么远:

    var Collection = require('ampersand-rest-collection');
    var LoneItem = require('../models/LoneItem');
    
    module.exports = Collection.extend({
      model: LoneItem,
      urlRoot: '/deeply/nested/path/',
      url: function() {
        return this.urlRoot + this.options.id + '/';
      },
      initialize: function(models, options) {
        this.options = options || {};
      },
      parse: function(response){
        return response.arrayAttribute;
      }
    });
    

    从外观上看:

    var myCollection = new GroupOfItems([], {id: 'someID'});
    myCollection.fetch();
    

    换句话说,我所要做的只是将 Backbone.Collection 更改为 & 符号,就是这样。

    fetchById 旨在通过单独的 REST 调用获取集合的成员。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2015-05-30
      • 2020-11-30
      • 1970-01-01
      • 2013-01-04
      相关资源
      最近更新 更多