Hi,
Via Function#bind[1], more here[2]. Or you can just use a straight-
forward closure[3], like this:
loadItemsFromUrl: function(url) {
var self = this;
new Ajax.Request(url, {
method: 'get',
onSuccess: function(transport) {
// Here, 'self' references the instance, so:
if (transport.responseJSON &&
transport.responseJSON.items) {
self.items = transport.responseJSON.items;
}
}
});
}
Whether to use Function#bind or a closure depends on your needs. If
you're already defining the function inline (as in your example),
you're already creating a closure and so you may as well get the
benefit of it. :-) But if the function you're calling is defined
elsewhere and you're just referencing it, like so:
loadItemsFromUrl: function(url) {
var self = this;
new Ajax.Request(url, {
method: 'get',
onSuccess: theFunction
});
}
...then you're not creating a closure in that location and so I'd
probably use Function#bind:
loadItemsFromUrl: function(url) {
var self = this;
new Ajax.Request(url, {
method: 'get',
onSuccess: theFunction.bind(this)
});
}
...because the closure Function#bind creates for you has low overhead.
[1] http://prototypejs.org/api/function/bind
[2]
http://proto-scripty.wikidot.com/prototype:tip-using-an-instance-method-as-a-callback-or-event-handler
[3] http://blog.niftysnippets.org/2008/02/closures-are-not-complicated.html
HTH,
--
T.J. Crowder
tj / crowder software / com
Independent Software Engineer, consulting services available
On Jun 2, 9:48 pm, Col <[email protected]> wrote:
> I'm a little confused about context and how to access things correctly
> when my ajax request onSuccess function runs.
>
> My code currently looks something like this:
>
> var MyObject = Class.create({
> initialize: function() {
> this.items = [];
> },
> loadItemsFromUrl: function(url) {
> new Ajax.Request(url, {
> method: 'get',
> onSuccess: function(transport) {
> // how can I access 'this.items' from here ???
> }
> });
> }
>
> });
>
> var myObject = new MyObject();
> myObject.loadItemsFromUrl('http://www.blah.com/items');
>
> I realise that 'this' will not actually point to the instance of
> myObject when the callback is run but how CAN I access it ?
>
> thanks
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"Prototype & script.aculo.us" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/prototype-scriptaculous?hl=en
-~----------~----~----~----~------~----~------~--~---