あなたが望むものを達成する方法はたくさんあるはずです。以下のコードは、カスタム イベントを処理する jQuery の機能を利用して、"疎結合" オブザーバー パターンを提供します。
$(function() {
//Establish the two dozen functions that will be called.
var functionList = [
function() {...},
function() {...},
function() {...},
...
];
var gridParams = {offset:10, pitch:65};//Example grid parameters. Adjust as necessary.
//Establish a custom event and its handler.
var $myElement = $("#myID").data('lastIndex', -1).on('hasMoved', function() {
$element = $(this);
var pos = $element.position();//Position of the moved element relative to its offset parent.
var index = Math.floor((pos.left - gridParams.offset) / gridParams.pitch);//Example algorithm for converting pos.left to grid index.
if(index !== $element.data('lastIndex')) {//Has latest movement align the element with the next grid cell?
functionList[index](index, $element);//Call the selected function.
$element.data('lastIndex', index);//Remember index so it can be tested mext time.
}
});
});
$(function() {
//(Existing) function that moves the element must trigger the custom 'hasMoved' event after the postition has been changed.
function moveElement() {
...
...
...
myElement.trigger('hasMoved');//loosely coupled 'hasMoved' functionality.
}
var movementInterval = setInterval(moveElement, 100);
});
ご覧のとおり、疎結合の利点は、関数とそれを呼び出すコードが異なるスコープにある可能性があり.on('hasMoved', function() {...}
、myElement.trigger('hasMoved')
異なる$(function(){...})
構造にあることです。
他の関数を追加して位置を変更したい場合myElement
(例: first、previous、next、last 関数)、要素を移動した後、それらは単に「hasMoved」をトリガーして、2 つのうちの適切な 1 つが確実に移動されるようにする必要があります。スコープを気にする必要なく、多数の関数が呼び出されます。
確認する必要がある唯一のことは、カスタム イベント ハンドラーによって呼び出すことができるように、20 個の関数のスコープが設定されていることです (つまり、グローバル スコープまでの同じスコープまたは外側のスコープ内にある)。
私は多くの仮定をしなければならなかったので、上記のコードは 100% 正しいわけではありませんが、うまくいけば先へ進む道を提供してくれるでしょう。