为什么我不能用Backbone.Collection作为一个泛型集合?有没有做到这一点的实现? [英] Why can't I use Backbone.Collection as a generic collection? Is there an implementation that does this?

查看:72
本文介绍了为什么我不能用Backbone.Collection作为一个泛型集合?有没有做到这一点的实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我问<一个href=\"http://stackoverflow.com/questions/19694938/why-cant-i-make-a-backbone-collection-of-backbone-views\">this问题并意识到 Backbone.Collection 是严格用于 Backbone.Models ,我有点失望的。

After I asked this question and realized that Backbone.Collections are strictly for Backbone.Models, I'm a little disappointed.

我希望的:

请下划线的方式更加面向对象的:

Make underscore's methods more object oriented:

_.invoke(myCollection, 'method');  ==>  myCollection.invoke('method');

我承认,微小的差别,但仍然看起来不错。

I'll admit, minor difference, yet still it seems nice.

我会碰上,如果我使用的是什么问题 Backbone.Collection 非 - Backbone.Models

What problems will I run into if I use Backbone.Collection for non-Backbone.Models?

是否有任何现有的实现,或者一个简单的方法,使一个普通的下划线集合类?

推荐答案

虽然你不能用一个骨干收藏不使用的机型,我想出了一个巧妙的方式混合在强调入阵的原型:

While you can't use a Backbone Collection without using models, I came up with a clever way to mix in underscore into the Array prototype:

// This self-executing function pulls all the functions in the _ object and sticks them
// into the Array.prototype
(function () {
    var mapUnderscoreProperty = function (prp) {
        // This is a new function that uses underscore on the current array object
        Array.prototype[prp] = function () {
            // It builds an argument array to call with here
            var argumentsArray = [this];
            for (var i = 0; i < arguments.length; ++i) {
                argumentsArray.push(arguments[i]);
            }

            // Important to note: This strips the ability to rebind the context
            // of the underscore call
            return _[prp].apply(undefined, argumentsArray);
        };
    };

    // Loops over all properties in _, and adds the functions to the Array prototype
    for (var prop in _) {
        if (_.isFunction(_[prop])) {
            mapUnderscoreProperty(prop);
        }
    }
})();

下面是如何使用新的阵列原型的例子:

Here is an example of how to use the new Array prototypes:

var test = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

console.log(test.filter(function (item) {
    return item > 2 && item < 7;
})); // Logs [3, 4, 5, 6]
console.log(test); // Logs the entire array unchanged

这个解决方案可能增加更多的阵列比原型实际上是有用的,但它可以让你的大部分功能。另一种解决方案是只补充一点,有一个迭代器参数的功能,但是这对你是一个开始。

This solution might add more to the Array prototype than is actually useful, but it gets you the bulk of the functions. Another solution would be to only add functions that have an iterator argument, but this is a start for you.

这篇关于为什么我不能用Backbone.Collection作为一个泛型集合?有没有做到这一点的实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆