I run into problems to pass a javascript object context into the callback handler of a JSONP ajax request, when the ajax provider predefines its callback. (Flickr is the service provider).
I'll give a simplified example:
function Person(anId) { this.name; this.id = anId; var self = this; this.loadName = function() { $.ajax({ url: "jsonp.json", dataType: "jsonp", jsonpCallback : "handleJSON", data : {id: this.id}, context: self, success: function (data) { self.name = data.name; } }); } } var handleJSON = function(data) { console.log("received " + data.name ); } var a = new Person(234); a.loadName(); var b = new Person(345); b.loadName();
The example above works perfectly, the console outputs the line of the handleJSON function. But in this function I don't have a reference to the original object that's calling it. I want that the success function is called instead: here I can refer to the self variable.
There are several possible solutions, but I don't get any running.
Currently I found a solution with the jquery-jsonp from google code. But still I'm very curious how to solve the problem as described at 2. Because I think the jQuery reference states that it could be handled like that. What makes me dependable on less third party libraries.
Can someone show me how to access the context in a JSONP callback handler using jQuery?
Just leave the jsonpCallback
property alone, and let jQuery create the function that gets called and it's function name. That function will call the success callback that you specify, with the context you specify.
function Person(anId) {
this.name;
this.id = anId;
this.loadName = function() {
$.ajax({
url: "jsonp.json",
dataType: "jsonp",
data : {id: this.id},
context: this,
success: function (data) {
this.name = data.name;
}
});
}
}
var a = new Person(234);
a.loadName();
var b = new Person(345);
b.loadName();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With