首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >嵌套Backbone.js集合的更好解决方案

嵌套Backbone.js集合的更好解决方案
EN

Stack Overflow用户
提问于 2012-05-02 15:26:09
回答 4查看 8.2K关注 0票数 17

我的许多主干模型经常处理嵌套模型和集合,到目前为止,我手动使用defaultsparsetoJSON的组合来实现嵌套:

代码语言:javascript
复制
ACME.Supplier = Backbone.Model.extend({
    defaults: function() {
        return {
            contacts: new ACME.Contacts(),
            tags: new ACME.Tags(),
            attachments: new ACME.Attachments()
        };
    },

    parse: function(res) {
        if (res.contacts) res.contacts = new ACME.Contacts(res.contacts);
        if (res.tags) res.tags = new ACME.Tags(res.tags);
        if (res.attachments) res.attachments = new ACME.Attachments(res.attachments);

        return res;
    }
});

ACME.Tag = Backbone.Model.extend({
    toJSON: function() {
        return _.pick(this.attributes, 'id', 'name', 'type');
    }
});

我看过一些插件,它们的功能与上面的基本相同,但控制更少,模板更多,所以我想知道是否有人有更优雅的解决方案来解决这个常见的Backbone.js问题。

编辑:I最终采用了以下方法:

代码语言:javascript
复制
ACME.Supplier = Backbone.Model.extend({
    initialize: function(options) {
        this.tags = new ACME.Tags(options.tags);
    },

    parse: function(res) {
        res.tags && this.tags.reset(res.tags);

        return res;
    }
});

ACME.Tag = Backbone.Model.extend({
    toJSON: function() {
        return _.pick(this.attributes, 'id', 'name', 'type');
    }
});

值得注意的是,后来我发现您需要通过options对象将嵌套模型/集合数据从构造函数传递到嵌套模型的构造函数。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-05-03 00:55:39

我不认为你的方法有任何问题。

如果需要特殊的解析行为,可以重写Model.parse()方法。

我唯一想要改变的就是这样的事情:

代码语言:javascript
复制
if (res.tags) res.tags = new ACME.Tags(res.tags);

为此:

代码语言:javascript
复制
if (res.tags) this.tags.reset(res.tags);

因为你已经有了一个ACME.Tags集合的实例,所以我会重用它。

另外,我真的不喜欢defaults实现,我习惯于在Model.initialize()中进行这种初始化,但我认为这是个人喜好的问题。

票数 8
EN

Stack Overflow用户

发布于 2012-10-29 21:48:01

我发现使用这种方法,供应商的toJSON函数将会过时,所以把它的JSON状态从孩子的数据重新组装回来可能是个好主意。

代码语言:javascript
复制
ACME.Supplier = Backbone.Model.extend({
    initialize: function(options) {
        this.tags = new ACME.Tags(options.tags);
    },

    parse: function(res) {
        res.tags && this.tags.reset(res.tags);

        return res;
    },

    toJSON: function({
        return _.extend(
            _.pick(this.attributes, 'id', 'attr1', 'attr2'), {
            tags: this.tags.toJSON(),
        });
    })

});

票数 3
EN

Stack Overflow用户

发布于 2013-09-25 02:45:46

我们不想添加另一个框架来实现这一点,所以我们将其抽象在一个基础模型类中。下面是如何声明和使用它(available as a gist):

代码语言:javascript
复制
// Declaration

window.app.viewer.Model.GallerySection = window.app.Model.BaseModel.extend({
  nestedTypes: {
    background: window.app.viewer.Model.Image,
    images: window.app.viewer.Collection.MediaCollection
  }
});

// Usage

var gallery = new window.app.viewer.Model.GallerySection({
    background: { url: 'http://example.com/example.jpg' },
    images: [
        { url: 'http://example.com/1.jpg' },
        { url: 'http://example.com/2.jpg' },
        { url: 'http://example.com/3.jpg' }
    ],
    title: 'Wow'
}); // (fetch will work equally well)

console.log(gallery.get('background')); // window.app.viewer.Model.Image
console.log(gallery.get('images')); // window.app.viewer.Collection.MediaCollection
console.log(gallery.get('title')); // plain string

它与settoJSON的效果一样好。

这是BaseModel

代码语言:javascript
复制
window.app.Model.BaseModel = Backbone.Model.extend({
  constructor: function () {
    if (this.nestedTypes) {
      this.checkNestedTypes();
    }

    Backbone.Model.apply(this, arguments);
  },

  set: function (key, val, options) {
    var attrs;

    /* jshint -W116 */
    /* jshint -W030 */
    // Code below taken from Backbone 1.0 to allow different parameter styles
    if (key == null) return this;
    if (typeof key === 'object') {
      attrs = key;
      options = val;
    } else {
      (attrs = {})[key] = val;
    }
    options || (options = {});
    // Code above taken from Backbone 1.0 to allow different parameter styles
    /* jshint +W116 */
    /* jshint +W030 */

    // What we're trying to do here is to instantiate Backbone models and collections
    // with types defined in this.nestedTypes, and use them instead of plain objects in attrs.

    if (this.nestedTypes) {
      attrs = this.mapAttributes(attrs, this.deserializeAttribute);
    }

    return Backbone.Model.prototype.set.call(this, attrs, options);
  },

  toJSON: function () {
    var json = Backbone.Model.prototype.toJSON.apply(this, arguments);

    if (this.nestedTypes) {
      json = this.mapAttributes(json, this.serializeAttribute);
    }

    return json;
  },

  mapAttributes: function (attrs, transform) {
    transform = _.bind(transform, this);
    var result = {};

    _.each(attrs, function (val, key) {
      result[key] = transform(val, key);
    }, this);

    return result;
  },

  serializeAttribute: function (val, key) {
    var NestedType = this.nestedTypes[key];
    if (!NestedType) {
      return val;
    }

    if (_.isNull(val) || _.isUndefined(val)) {
      return val;
    }

    return val.toJSON();
  },

  deserializeAttribute: function (val, key) {
    var NestedType = this.nestedTypes[key];
    if (!NestedType) {
      return val;
    }

    var isCollection = this.isTypeASubtypeOf(NestedType, Backbone.Collection),
        child;

    if (val instanceof Backbone.Model || val instanceof Backbone.Collection) {
      child = val;
    } else if (!isCollection && (_.isNull(val) || _.isUndefined(val))) {
      child = null;
    } else {
      child = new NestedType(val);
    }

    var prevChild = this.get(key);

    // Return existing model if it is equal to child's attributes

    if (!isCollection && child && prevChild && _.isEqual(prevChild.attributes, child.attributes)) {
      return prevChild;
    }

    return child;
  },

  isTypeASubtypeOf: function (DerivedType, BaseType) {
    // Go up the tree, using Backbone's __super__.
    // This is not exactly encouraged by the docs, but I found no other way.

    if (_.isUndefined(DerivedType['__super__'])) {
      return false;
    }

    var ParentType = DerivedType['__super__'].constructor;
    if (ParentType === BaseType) {
      return true;
    }

    return this.isTypeASubtypeOf(ParentType, BaseType);
  },

  checkNestedTypes: function () {
    _.each(this.nestedTypes, function (val, key) {
      if (!_.isFunction(val)) {
        console.log('Not a function:', val);
        throw new Error('Invalid nestedTypes declaration for key ' + key + ': expected a function');
      }
    });
  },
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10409436

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档