次の関数を追加して、いくつかのコレクションを逆方向に反復できるようにしました。
jQuery.reverseEach = function (object, callback, args) {
var reversed = $(object).get().reverse();
return $(reversed).each(callback, args);
};
次のように呼び出すと、うまく機能します。
$.reverseEach($('#selectedSortItems option:selected'), function() {
$(this).insertAfter($(this).next());
});
しかし、私は自分のシンタックス シュガーが好きなので、巧妙にチェーン化できるようにしたかったのです。jQuery のプロトタイプに元の reverseEach 関数への参照を追加しました。
jQuery.prototype.reverseEach = function(callback, args) {
return jQuery.reverseEach(this, callback, args);
};
そして今、私はそれを次のように呼び出すことができます:
$('#selectedSortItems option:selected').reverseEach(function () {
$(this).insertAfter($(this).next());
});
しかし、jQuery.fn.extend 関数は、プロトタイプを参照する必要なく、1 つのステップで同じことを行うと思いました。次のように、jQuery.fn.extend 関数を使用しようとしました。
jQuery.fn.extend({
reverseEach: function(object, callback, args) {
var reversed = $(object).get().reverse();
return $(reversed).each(callback, args);
}
});
しかし、連鎖したメソッドをそのように実行すると、次のエラーが表示されます: プロパティ 'call' の値を取得できません: オブジェクトが null または未定義です。
jQuery.fn.extend メソッドの何が間違っていますか? 私は完全に間違ったアプローチをとっていますか、それとも単純なものが欠けているだけですか?
ありがとう!