سؤال

I have the following function:

function checkTag(dataVal) {
    return $.ajax({
        data: {input: dataVal}
        ...
    });
}

Currently, on keyup, that function is called as such:

$("#element").on("keyup", function() {
    var tag = $(this).val();
    checkTag(tag).done(function(data) {
        ...
    });
});

and that works without an issue. However, later in my code, I want to call that deferred.done() again. I've therefore created a function as such:

function checkTagDone(data) {
    ...
}

And tried to call it like this:

checkTag(tag).done(checkTagDone(data));

and also tried:

$.when(checkTag(tag)).done(checkTagDone(data));

but in both instances I get variable 'data' is not found at console. I've clearly misunderstood the usage of deferred.done however there must be a way of iterating over the same deferred.done without having to replicate the code. I can find documentation to support multiple deferred.done instances following a single AJAX call, but nowhere can I find a solution to replicate the same deferred.done following multiple AJAX calls.

Relevant jQuery for object htmlinputelement issue:

function checkTagDone(data, tag) {    
    if (data) {
        ...
        //Create span around tag input
        $(".tree").last().append("<span class='tag'>"+tag+"</span>").fadeIn(500).val("");
        ...
    }
}
هل كانت مفيدة؟

المحلول

You need to pass the function reference to done like and pass the value of the tag to the checkTag method(Because from what I can see tag is a local variable in the keyup scope.).

checkTag($("#element").val()).done(checkTagDone);

var tag = $("#element").val();
checkTag(tag).done(function (data) {
    checkTagDone(data, tag);
});

نصائح أخرى

Ryan, you appear to have two choices :

Leave the event handler as it is, and trigger the keyup event to re-perform ajax on the element's current value

$("#element").trigger('keyup');

This can be performed at any point in your code. There are no scope issues as all code has access to the DOM.

Modify the event handler such that it saves the most recent ajax promise in an outer scope

var lastKeyupPromise;
...
$("#element").on('keyup', function() {
    lastKeyupPromise = checkTag($(this).val()).done(checkTagDone);
});

Then, elsewhere in your code :

if(lastKeyupPromise) { // safety is required as `lastKeyupPromise` may still be undefined
    lastKeyupPromise.done(checkTagDone);
}

This can be performed at any point in your code providing lastKeyupPromise and checkTagDone are in scope.

The advantages of the second aproach are :

  • No need to perform another ajax request.
  • You are not limited to executing checkTagDone. You can choose to execute whatever is appropriate at that point in your code.

For example :

if(lastKeyupPromise) {
    lastKeyupPromise.done(someOtherHandler);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top