Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RaphaelJS Set.forEach()

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.

like image 682
Artur Keyan Avatar asked Jan 27 '12 14:01

Artur Keyan


3 Answers

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?

like image 103
limoragni Avatar answered Oct 17 '22 09:10

limoragni


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();
like image 39
Grooveek Avatar answered Oct 17 '22 08:10

Grooveek


Some things that are missing from the Raphael forEach documentation:

What is passed to the function you define

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:

  1. The Raphael element that is currently being looked at.
  2. The index number indicating the position of that Raphael element in the set.

this in the scope of a cycle of Raphael's forEach is unchanged from the surrounding function (unlike jQuery's .each()).

Possible crashes or unexpected behaviour

  • Unlike jQuery's .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.
  • As mentioned, Raphael's .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.
like image 2
user56reinstatemonica8 Avatar answered Oct 17 '22 10:10

user56reinstatemonica8