I read in the documentation raphaeljs description of Set.forEach, and can't understand how it works. Please can anyone give me an example of usage.
Here you have a working example:
http://jsfiddle.net/9X6rM/
And this is the important part of It:
set.forEach(function(e){
e.attr({fill:'#000'})
})
Its a little bit tricky at first, but its pretty handy when you get it. You need to pass to the forEach()
method the function that you want to execute on each element, and this function need to have, like an argument, a variable name to bind to the element. So in this case e
is the rectangle that is being processed. Got it?
This thread is pretty helpful in understanding how forEach
works
Edit :
You have a working example in the Raphaël Documentation
Raphael.el.red = function () {
this.attr({fill: "#f00"});
};
Raphael.st.red = function () {
this.forEach(function (el) {
el.red();
});
};
// then use it
paper.set(paper.circle(100, 100, 20), paper.circle(110, 100, 20)).red();
Some things that are missing from the Raphael forEach
documentation:
set.forEach(function(element, index){
element.attr({fill:'#000'});
alert('This is the element that can be accessed as set['+index+']');
})
Two arguments are passed passed to the callback function:
this
in the scope of a cycle of Raphael's forEach
is unchanged from the surrounding function (unlike jQuery's .each()
).
.each()
function, Raphael's .forEach()
crashes out if it's passed a singular Raphael element instead of a set. If a variable might contain one element, or might contain a set of multiple elements, check what type of Raphael object it is first..forEach()
doesn't create a closure like in jQuery - it's really just an iteration through an array. Variables in each iteration aren't 'frozen' in that iteration, they can be overwritten by following iterations.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