Why can't I use Backbone.Collection as a general collection? Is there an implementation that does this?

After I asked this question and realized what is Backbone.Collectionstrictly for Backbone.Models, I am a little disappointed.

What I was hoping for:

Make underline methods more object oriented:

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

I admit, a little difference, but still seems nice.

What problems will I use if I use Backbone.Collectionto not Backbone.Models?

Are there any existing implementations or an easy way to create a common underscore collection class?

+4
source share
1 answer

Backbone Collection , Array:

// 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);
        }
    }
})();

Array:

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

Array , , . , , .

+1

All Articles