在我询问之后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/