1

I have this code:

var callbackAfterLoad = function(data, ecBlock) {
    ecBlock.html(data);
    ecBlock.slideDown();
}

function bindevents(userInput, ecBlock, callbackAfterLoad) {
    userInput.keyup(function () {
        delay(function () {
            $.post("/preview", {content:userInput.val()}, callbackAfterLoad(data, ecBlock));
        }, 500);
    });
 }

And this error:

Uncaught ReferenceError: data is not defined 

But when I check out jQuery examples

$.post("test.php", function(data) {
  alert("Data Loaded: " + data);
});

Why do I got this error ? Why do jQuery example is working and not mine ? (we cannot add parameters ?). Is the default $.post callback defined and his signature cannot be overriden ?

2 Answers 2

6

The third argument in $.post should be a function, but when you do this:

$.post("/preview", {content:userInput.val()}, callbackAfterLoad(data, ecBlock))

The third argument is not the function, but the return value of the function. Like this:

fn = callbackAfterLoad   // function reference
fn = callbackAfterLoad() // function execution and return value reference

And when executed in your example, data is not available yet. The correct syntax would be:

$.post("/preview", {content:userInput.val()}, callbackAfterLoad)

If you need to pass custom arguments to your callback, you can create a new proxy function like this:

var callback = function(data) {
    callbackAfterLoad.call(this, data, ecBlock);
};
$.post("/preview", {content:userInput.val()}, callback);
Sign up to request clarification or add additional context in comments.

Comments

1

Try to use .post method in little bit another way:

$.post("/preview", {content:userInput.val()}, function(data){ callbackAfterLoad(data, ecBlock)} );

Your example doesn't work because you're immediately calling to callbackAfterLoad , before the .post actually "happens" and returns data. In jQuery example the callback function is only registered as handler but not firing immediately.

2 Comments

Thanks! This is actually working great! But why "function(data)" cannot be called with another anonymous function ?
@YoH what do you mean exactly. when it goes like this: function(data){ callbackAfterLoad(data, ecBlock)} it is actually creates anonymous function that uses data which post returns and ecBlock that came as bindevents function argument

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.