4

この質問Backbone.Collectionをして、 s が厳密に に対応していることに気付いた後Backbone.Models、少しがっかりしました。

私が望んでいたこと:

アンダースコアのメソッドをよりオブジェクト指向にする:

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

多少の違いは認めますが、それでもいいようです。

Backbone.Collection以外に使用すると、どのような問題が発生しBackbone.Modelsますか?

既存の実装、または一般的なアンダースコア コレクション クラスを作成する簡単な方法はありますか?

4

1 に答える 1

1

モデルを使用せずにバックボーン コレクションを使用することはできませんが、私は 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 つの解決策は、反復子引数を持つ関数のみを追加することですが、これは最初の一歩です。

于 2013-11-06T16:29:38.573 に答える