javascript 设置主干集合中所有模型的属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13887089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:03:03  来源:igfitidea点击:

set attribute of all models in backbone collection

javascriptbackbone.jsunderscore.jsbackbone.js-collections

提问by sublime

I understand that using pluck method we can get an array of attributes of each model inside a backbone collection

我知道使用 pluck 方法我们可以在主干集合中获取每个模型的属性数组

var idsInCollection = collection.pluck('id'); // outputs ["id1","id2"...]

I want to if there is a method that sets up an attribute to each model in the collection,

我想如果有一种方法可以为集合中的每个模型设置一个属性,

var urlArray = ["https://url1", "https://url1" ...];
collection.WHAT_IS_THIS_METHOD({"urls": urlArray});

采纳答案by David Hellsing

I don't there is a method for it, but you can try:

我没有它的方法,但你可以尝试:

collection.forEach(function(model, index) {
    model.set(url, urlArray[index]);
});

回答by machineghost

There's not exactly a pre-existing method, but invokelet's you do something similar in a single line:

没有完全预先存在的方法,但invoke让我们在一行中执行类似的操作:

collection.invoke('set', {"urls": urlArray});

If you wanted to make a re-usable set method on all of your collections, you could do the following:

如果您想在所有集合上创建一个可重用的 set 方法,您可以执行以下操作:

var YourCollection = Backbone.Collection.extend({
    set: function(attributes) {
        this.invoke('set', attributes);
        // NOTE: This would need to get a little more complex to support the
        //       set(key, value) syntax
    }
});

* EDIT *

* 编辑 *

Backbone has since added its own setmethod, and if you overwrite it you'll completely break your Collection. Therefore the above example should really be renamed to setModelAttributes, or anything else which isn't set.

Backbone 已经添加了它自己的set方法,如果你覆盖它,你将完全破坏你的Collection. 因此,上面的示例确实应该重命名为setModelAttributes,或者其他任何不是set.

回答by Matt Fletcher

Expanding on David's answer, you can easily put this functionality into a custom method on the collection. Here's my way of doing it using coffeescript:

扩展大卫的答案,您可以轻松地将此功能放入集合的自定义方法中。这是我使用 coffeescript 的方法:

class Collection extends Backbone.Collection
  setAll: () ->
    _args = arguments
    @models.forEach (model) -> model.set _args...

class SomeCollection extends Collection
  url: '/some-endpoint.json'

myLovelyCollection = new SomeCollection()
myLovelyCollection.fetch
  success: (collection, response) ->
    collection.setAll someVar: true
    collection.setAll anotherVar, 'test'

If you wanted to do it in vanilla JS it's exactly the same but not harnessing the power of classes or splats. So more like:

如果你想在 vanilla JS 中做到这一点,它是完全相同的,但没有利用类或 splats 的力量。所以更像是:

var Collection = Backbone.Collection.extend({
  setAll: function () {
    var _args = arguments;
    this.models.forEach(function (model) {
      model.set.apply(model, _args);
    });
  }
});

回答by relic

Just thought I'd post my slightly updated method based on machineghost's version. This uses lodash invokeMap method instead of underscore's invoke. It supports the same optional syntax as the standard model.set method ... e.g. ('prop', 'val') or ({prop: 'val', prop: 'val'}) as well accepting and passing an options object.

只是想我会根据 machineghost 的版本发布我稍微更新的方法。这使用 lodash invokeMap 方法而不是下划线的调用。它支持与标准 model.set 方法相同的可选语法……例如 ('prop', 'val') 或 ({prop: 'val', prop: 'val'}) 以及接受和传递选项对象.

var YourCollection = Backbone.Collection.extend({
    setModels: function(key, val, options) {
        var attrs;

        if (typeof key === 'object') {
            attrs = key;
            options = val;
        } else {
            (attrs = {})[key] = val;
        }

        if (attrs) {
            _.invokeMap(this, 'set', attrs, options);
        }

        return this;
    }
});

回答by TheProfessor117

If you are using invoke the syntax according to the underscore site should be _.invoke(list, methodName, *arguments) http://underscorejs.org/#invoke

如果您根据下划线站点使用调用语法应该是 _.invoke(list, methodName, *arguments) http://underscorejs.org/#invoke

So the above function mentioned by machineghostshould be

所以上面machineghost提到的函数应该是

collection.invoke({'url': someURL},'set');

Hope that helps :)

希望有帮助:)