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…
.callcalls a function with explicit context given by the first argument, socallback.call(msg, count)calls the callback function withmsgset as context (thethisvalue inside the callback function for this call) andcountas a first argument.So you probably want
callback( msg, count )orcallback.call( namespace, msg, count );which means thatthisinside the callback will refer tonamespacefor that call.