Set.forEach method

470 views
Skip to first unread message

Ben

unread,
Oct 26, 2011, 11:10:36 PM10/26/11
to Raphaël
Excuse my ignorance, but could someone explain set.forEach? The method
calls for (callback, thisArg), which is fine, but it seems like
thisArg isn't a parameter you should pass, with a function parameters
object making somewhat more sense.

This is forEach:
function (callback, thisArg) {
for (var i = 0, ii = this.items.length; i < ii; i++) {
if (callback.call(thisArg, this.items[i], i) === false) {
return this;
}
}
return this;
}

Wouldn't it be more powerful if you changed it to:
function (callback, thisArg) {
for (var i = 0, ii = this.items.length; i < ii; i++) {
if (callback.call(this.items[i], thisArgs, i) === false) {
return this;
}
}
return this;
}

Perhaps forEach is not designed for use with custom methods, but could
someone explain the reason it is this way?

Thanks,



Jesse Silverstein

unread,
Nov 3, 2011, 7:22:52 AM11/3/11
to Raphaël
thisArg is the context that the 'callback' should be called from, or
in other words, what "this" represents when that callback is fired. I
believe you are asking if it is possible to send additional arguments
in to the forEach function, though your example does not accomplish
that. The easiest way to send additional arguments through forEach
without modifying the library is to wrap them in a closure:

var myA, myB, set=paper.set();
set.forEach( (function(a,b){ return function(el, i)
{ el.data("a",a).data("b",b); }; } )( myA, myB ) );

This lets the function fire with myA and myB available within the
function context (as a and b), but also does not leave behind residual
anonymous functions for garbage collector to fight with.

Hope this helps.

Ben

unread,
Nov 7, 2011, 8:57:34 PM11/7/11
to Raphaël
Thanks for your reply, especially for the code snippet, but that
wasn't exactly what I was saying. I was trying to say it would be more
intuitive if each item in the set were passed in as the context item
(thisArg) as opposed to a context object that you pass in. I was
coming from the perspective of never having used the method before,
and I had to look at the source to figure out how to use the method.

Is there a collaborative wiki or anything that people can have some
peer reviewed input to expand on the documentation Raphael provides?
If I had a complaint about Raphael so far, I believe it would be lack
of thorough documentation.

Thanks again.
Reply all
Reply to author
Forward
0 new messages