0

再帰的な $.ajax() 呼び出しを介してサーバーから情報を取得しようとしていますが、バインドされている要素が削除されたときにそれらの呼び出しを停止したいと考えています。

function check_for_update($element) {

    // this is where I need your help fellas:
    $does_this_element_currently_reside_in_the_dom = ????? ; 

    if ($does_this_element_currently_reside_in_the_dom) {
        $.ajax({ ... });
        setTimeout(function() { 
            check_for_update($element) 
        }, 1000);
    } 
}
$ele = $('<div id="element1"></div>');

// start recursion
check_for_update($ele);

要素を DOM から削除すると、再帰が停止します。

$ele.remove();

要素はさまざまな方法で削除できるため、シナリオごとにコールバックを記述するのは面倒です。(つまり、削除可能、その親を削除可能、その親の親を削除可能...)。

ありがとう!!

4

2 に答える 2

1

要素が setTimeout 内に存在するかどうかを確認し、タイマーをクリアします。下記参照、

function check_for_update($element) {

    var timer; //added
    // this is where I need your help fellas:
    $does_this_element_currently_reside_in_the_dom = ????? ; 

    if ($does_this_element_currently_reside_in_the_dom) {
        $.ajax({ ... });
        //v-- Added timer var
        timer = setTimeout(function() { 
            if ($('#element1').length) clearTimeout(timer); //Added
            check_for_update($element) 
        }, 1000);
    } 
}
$ele = $('<div id="element1"></div>');

// start recursion
check_for_update($ele);
于 2013-03-07T16:21:58.360 に答える
0

助けてくれてありがとう!あなたはたくさんの紳士です!

再帰関数内にある私のソリューションは次のとおりです。

function check_for_update($element) {

    // check for the check_for_update_id attribute
    if ($element.attr('check_for_update_id') === undefined) {
        // set the attribute if it's currently undefined
        d = new Date();
        check_for_update_id = String(d.getTime()) + String(d.getMilliseconds());
        $element.attr('check_for_update_id', check_for_update_id);
        }
    // create $element_new using the check_for_update_id attribute
    $element_new = $(  '[check_for_update_id=' + 
                        $element.attr('check_for_update_id') +
                       ']');

    // if $element has been removed from the DOM,
    // $element_new will not have a 'check_for_update_id' attribute
    if ($element_new.attr('check_for_update_id') !== undefined) {
        $.ajax({ ... });
        setTimeout(function() { 
            check_for_update($element_new);
        }, 1000);
    } 
}

要素が関数に初めて渡されるとき、属性'check_for_update_id'は$elementで未定義になります。現在未定義の場合、「check_for_update_id」が設定され、後続のすべてのsetTimeout()がcheck_for_update()関数を呼び出すと、$elementにこの「check_for_update_id」値が関連付けられます。衝突を避けるために、この関数が呼び出されるときに「check_for_update_id」を秒+ミリ秒に設定しました(これは私の目的には少しやり過ぎですが、申し訳ありませんが安全です)。

次に、'check_for_update_id'属性をセレクターとして使用して、関数内に$element_newが作成されます。

$element_new = $(  '[check_for_update_id=' + 
                    $element.attr('check_for_update_id' + 
                   ']');

setTimeout()の反復の間に$ elementが削除された場合、'check_for_update_id'属性は$element_newに対して未定義になり、setTimeout()は再度呼び出されません。

于 2013-03-07T17:24:35.203 に答える