javascript - 为什么我不能将 Backbone.Collection 用作通用集合?是否有执行此操作的实现?

标签 javascript backbone.js underscore.js

在我询问之后this question并意识到 Backbone.Collection 严格适用于 Backbone.Models,我有点失望。

我所希望的:

使 underscore 的方法更加面向对象:

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

我承认,差别很小,但看起来还是不错。

如果我对非Backbone.Models 使用Backbone.Collection 会遇到什么问题?

是否有任何现有的实现,或制作通用下划线集合类的简单方法?

最佳答案

虽然你不能在不使用模型的情况下使用 Backbone Collection,但我想出了一个巧妙的方法来将下划线混合到 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);
        }
    }
})();

这是一个如何使用新数组原型(prototype)的例子:

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 原型(prototype)添加比实际有用的更多内容,但它为您提供了大部分功能。另一种解决方案是仅添加具有迭代器参数的函数,但这对您来说只是一个开始。

关于javascript - 为什么我不能将 Backbone.Collection 用作通用集合?是否有执行此操作的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19695237/

相关文章:

php - 相当于这个简单 php 的 JavaScript

javascript - 如何使用远程内容中的按钮关闭模式?

javascript - 在刷新浏览器页面之前, meteor 流无法正常工作

inheritance - Backbone View 继承-调用父级导致递归

javascript - 每条路线上的主干路由器

javascript - 在 JavaScript 中使用 MapReduce

javascript - JQuery Cascade 函数在更改事件后不会立即触发

javascript - 我如何创建我自己的 watch 功能类似于javascript中的 Angular

javascript - 如果变量是全局变量,为什么需要将参数传递给 javascript 中的自执行函数?

javascript - 使用下划线减少连接?