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.
- I'll intercept the callback name that jQuery generates for me and put it as a value in the jsonpCallback parameter. I presume that this function delegates to the specified success function, from which I can access this. But I see no way how to obtain that generated name.
- I'll specify the context object like I did in the example. The jQuery docs states that this object would be available to the callback handler. However I cannot find how this context is exposed to e.g. the handleJSON function from my example.
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?