1

I wrote a function which I'm allowing a callback to be passed to. I then want to execute that with both the ajax repsonse, and another parameter.

My problem is the the callback is executed, and when I step through the code, it looks like the function is called with the proper parameters, however when actually stepping in to the callback function, the first parameter takes the value of whatever I assign to the second argument, and the second argument is undefined.

Here is my function:

namespace = {
fetch : function(sr, count, callback) {
    srCount = count ? count : '25'
    var sub;
    if (sr == 'frontpage'){
        sub = '';
    }else{
        sub = 'foo/' + sr + '/';
    };
    $.ajax({
        url: "http://www.example.com/"+sub+ ".json?count=" + count,
        dataType: "json",
        success: function(msg)
        {
            callback.call(msg, count)
        }
    })
};

Now, when I call it like this:

mynamespace.fetch($(this).attr('href'), 25, true, another namespace.createPost);

I would expect callback.call(msg, count) to resolve to callback.call(/*the ajax response*/, 25);

However, when I run it, I get msg == 25 and count == 'undefined'. I'm at a loss for why...

2
  • mynamespace.fetch($(this).attr('href'), 25, true, another namespace.createPost);. What's true for? Commented Dec 22, 2011 at 19:31
  • A remnant from old code that I copied and pasted... not actually used. Editing. Commented Dec 22, 2011 at 19:33

2 Answers 2

4

.call calls a function with explicit context given by the first argument, so callback.call(msg, count) calls the callback function with msg set as context (the this value inside the callback function for this call) and count as a first argument.

So you probably want callback( msg, count ) or callback.call( namespace, msg, count ); which means that this inside the callback will refer to namespace for that call.

Sign up to request clarification or add additional context in comments.

2 Comments

so put another way, call accepts X+1 parameters, where the first is the namespace the function will run in, and the remaining X are passed to the variable?
@ChrisSobolewski Well if by namespace you mean the value of this in the called function then yes, the arguments passed start after that either way. developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
1

$.ajax() function has a context parameter, which you can use for this purpose.

$.ajax({
  url: "http://www.example.com/"+sub+ ".json?count=" + count,
  context: "hello",
  dataType: "json",
  success: function(msg)
  {

    // here 'this' will be the 'hello' you specified for context while making the call.

    callback.call(msg, count)
  }
})

Comments

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.