Any way to access class attributes when using 'each' to iterate over an array?

1 view
Skip to first unread message

David Behler

unread,
Jul 7, 2009, 5:50:16 PM7/7/09
to Prototype & script.aculo.us
Why does this work:
var Deletr = Class.create({
initialize: function(options) {
var list = new Array();
$$('a.deletr').each(function(element) {
list.push(element);
});
}
});

But this does not?
var Deletr = Class.create({
initialize: function(options) {
this.list = new Array();
$$('a.deletr').each(function(element) {
this.list.push(element);
});
}
});

Firebug reports:
this.list is undefined
this.list.push(element);

Is there a way to access class attributes when I'm using each to
iterate over an array?
That would be really helpful!

Thanks
David

T.J. Crowder

unread,
Jul 8, 2009, 3:32:12 AM7/8/09
to Prototype & script.aculo.us
Hi,

Within the function called by #each, by default the context (the
"this" value) is a reference to the global object ('window', on web
browsers), not the same context as the code calling #each. This is
how JavaScript functions work: Unless you do something to explicitly
set "this" when calling them, they default to "this" being the global
object. More on this in this blog entry[1].

Because of that, #each has a second parameter[2] that sets the context
to use when calling the function. So this would work:

var Deletr = Class.create({
initialize: function(options) {
this.list = new Array();
$$('a.deletr').each(function(element) {
this.list.push(element);
}, this);
}

});

All I did there was add the second parameter to #each.

BTW, slightly OT, but you could replace that entire loop with this
line of code:

this.list = $$('a.deletr');

Unlike DOM methods, Prototype's various DOM wrappers return arrays,
not live lists, so you don't have to make a copy. If you really did
want to make a copy for some reason, you could do that via the $A
function[3] rather than an #each loop.

[1] http://blog.niftysnippets.org/2008/04/you-must-remember-this.html
[2] http://prototypejs.org/api/enumerable/each
[3] http://prototypejs.org/api/utility/dollar-a

HTH,
--
T.J. Crowder
tj / crowder software / com
Independent Software Engineer, consulting services available

David Behler

unread,
Jul 8, 2009, 4:03:32 AM7/8/09
to Prototype & script.aculo.us
Thanks alot! That worked!

I already guessed it had something to do with the context but didn't
know how to change it...
Reply all
Reply to author
Forward
0 new messages