简体   繁体   English

单一引用多个Backbone.Models

[英]Giving a single reference to multiple Backbone.Models

I have a Backbone.Model which looks something like: 我有一个Backbone.Model,看起来像:

var FooModel = Backbone.Model.extend({
    defaults: {
        details: '',
        operatingSystem: ''
    };
});

There are many instances of FooModel which are stored in a collection: FooModel的许多实例存储在一个集合中:

var FooCollection = Backbone.Collection.extend({
    model: FooModel
});

FooModel's OperatingSystem is a property which only needs to be calculated once and is derived asynchronously. FooModel的OperatingSystem是一个属性,仅需计算一次即可异步导出。 For example: 例如:

chrome.runtime.getPlatformInfo(function(platformInfo){
    console.log("Operating System: ", platformInfo.os);
});

If I perform this logic at the FooModel level then I will need to perform the logic every time I instantiate a FooModel. 如果我在FooModel级别执行此逻辑,则每次实例化FooModel时都需要执行该逻辑。 So, I think that this operation should be performed at a higher level. 因此,我认为应该在更高级别上执行此操作。 However, it is bad practice to give properties to a Backbone.Collection. 但是, 将属性赋予Backbone.Collection不好的做法。

As such, this leaves me thinking that I need a parent model: 因此,这让我觉得我需要一个父模型:

var FooParentModel = Backbone.Model.extend({
    defaults: {
        platformInfo: '',
        fooCollection: new FooCollection()
    },

    initialize: function() {
        chrome.runtime.getPlatformInfo(function(platformInfo){
            this.set('platformInfo', platformInfo);
        }.bind(this));
    },
    //  TODO: This will work incorrectly if ran before getPlatformInfo's callback
    createFoo: function(){
        this.get('fooCollection').create({
            details: 'hello, world',
            operatingSystem: this.get('platformDetails').os
        });
    }
});

This works and is semantically correct, but feels over-engineered. 这是可行的,并且在语义上是正确的,但是感觉过度设计。 The extra layer of abstraction feels unwarranted. 多余的抽象层感觉毫无用处。

Is this the appropriate way to go about giving a property to a model? 这是为模型赋予属性的适当方法吗?

Although Backbone Collections may not have attributes , they may have properties (as well as any object) which you can use to store shared data. 尽管Backbone Collections可能没有属性 ,但它们可能具有可用来存储共享数据的属性 (以及任何对象)。

var FooCollection = Backbone.Collection.extend({
    model: FooModel
    initialize: function() {
        this.platformInfo = null; // shared data
        chrome.runtime.getPlatformInfo(function(platformInfo){
            this.platformInfo = platformInfo;
        }.bind(this));
    },
    // wrapper to create a new model within the collection
    createFoo: function(details) {
        this.create({
            details: details,
            operatingSystem: this.platformInfo? this.platformInfo.os : ''
        });
    }});
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM