如何使用 Backbone.js 将过滤后的集合转换为 JSON?

发布于 2024-12-09 10:01:10 字数 664 浏览 0 评论 0原文

所以我在 Backbone 中有一个事件列表的集合。该集合有一个方法,可以根据传递给它的类别列表来过滤列表。

var Events = Backbone.Collection.extend({
    model: Event,
    url: settings.events_url,
    filtered: function(checked) {
        return this.filter(function(e) {
            if ($.inArray(e.get('category').name, checked) >= 0) {
                return true;
            } else {
                return false;
            }
        });
    }
});

我需要做的就是将此过滤后的集合转换为 JSON,就像处理整个集合一样。

var events = new Events();
events.toJSON();

但是,由于过滤后的集合不再是实际的集合,而是模型列表,因此我没有可用的 .toJSON() 方法。有没有办法将我的过滤集合转换为真实集合?或者有没有更简单的方法将其转换为 JSON?

谢谢!

So I have a collection in Backbone for a list of events. This collection has a method on it which filters the list based on a list of categories passed to it.

var Events = Backbone.Collection.extend({
    model: Event,
    url: settings.events_url,
    filtered: function(checked) {
        return this.filter(function(e) {
            if ($.inArray(e.get('category').name, checked) >= 0) {
                return true;
            } else {
                return false;
            }
        });
    }
});

What I need to be able to do is convert this filtered collection to JSON, the same way you would do the collection as a whole.

var events = new Events();
events.toJSON();

However, because the filtered collection is no longer an actual collection, but rather a list of models, I don't have the .toJSON() method available to me. Is there a way to convert my filtered collection to a real collection? Or is there an easier way to convert it to JSON?

Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

じ违心 2024-12-16 10:01:10

集合的构造函数可以将模型列表作为参数,因此:

var events = new Events();
var filteredEvents = new Events(events.filtered(true));
console.log(filteredEvents.toJSON());

The constructor for a collection can take a list of models as an argument so:

var events = new Events();
var filteredEvents = new Events(events.filtered(true));
console.log(filteredEvents.toJSON());
嘿哥们儿 2024-12-16 10:01:10

为什么不使用标准 API?

var checked = ['foo', 'bar', 'baz'],
    filtered = eventsCollection
        .chain()
        .filter(function(model) {
            return _.include(checked, model.get('category').name);
        })
        .invoke('toJSON')
        .value();

另外,Events.filterByCategoryName 方法名称更加明确。然而,我倾向于不在设计中实现太多“方便”的方法,而是直接使用它们来拥抱标准 API。

Why not make use of the standard API?

var checked = ['foo', 'bar', 'baz'],
    filtered = eventsCollection
        .chain()
        .filter(function(model) {
            return _.include(checked, model.get('category').name);
        })
        .invoke('toJSON')
        .value();

On a separate note, Events.filterByCategoryName method name is more explicit. However, I tend not to implement too many 'convenient' methods in my design and embrace the standard API by using them directly.

探春 2024-12-16 10:01:10

您还可以尝试以下操作:

    filtered: function(checked) {
        return _.map(this.filter(function(e) {
            return $.inArray(e.get('category').name, checked) >= 0
        }), function(model) {
            return model.toJSON();
        });
    }

从内到外开始:

  1. 对 this.filter 的调用将返回您已经拥有的过滤结果列表。
  2. _.map 将对它传递的数组的每个条目执行一个操作(它只是返回 model.toJSON() 的结果)。

You could also try something like:

    filtered: function(checked) {
        return _.map(this.filter(function(e) {
            return $.inArray(e.get('category').name, checked) >= 0
        }), function(model) {
            return model.toJSON();
        });
    }

Starting from the inside out:

  1. The call to this.filter will return the list of filtered results as you had it already.
  2. The _.map will perform an action on each entry of the array it is passed (it simply returns the result of model.toJSON()).
萌能量女王 2024-12-16 10:01:10

你可以这样做:

var myFilteredCollection = new Events(); 

_.each(myFilteredData, function(eventModel){
    myFilteredCollection.add(eventModel); 
});

myFilteredCollection.toJSON(); 

You can do like so :

var myFilteredCollection = new Events(); 

_.each(myFilteredData, function(eventModel){
    myFilteredCollection.add(eventModel); 
});

myFilteredCollection.toJSON(); 
标点 2024-12-16 10:01:10

我解决这个问题的方法是在集合上运行一个reduce函数。这样做的优点是,您只需对集合本身执行 1 次传递,仅记住有效的模型,并在通过验证时返回模型的 JSON。

其他用于构建新集合的解决方案在性能方面非常糟糕。

    getValidItems: function () {
        //return only valid items as json
        return this.collection.reduce(function (validItems, row) {
            if (row.isValid()) {
                validItems.push(row.toJSON());
            }
            return validItems;
        }, []);
    },


    //somewhere where you save
    save: function() {
        var validItems = this.getValidItems();
        //do something with valid items
    }

The way I solved it is running a reduce function on the collection. The advantage of this is that you only do a 1 pass on the collection itself, remembering only the valid models, and returning the JSON of the model if they pass validation.

The other solutions offered to build a new collection which is performance wise - terrible.

    getValidItems: function () {
        //return only valid items as json
        return this.collection.reduce(function (validItems, row) {
            if (row.isValid()) {
                validItems.push(row.toJSON());
            }
            return validItems;
        }, []);
    },


    //somewhere where you save
    save: function() {
        var validItems = this.getValidItems();
        //do something with valid items
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文