RaphaelJS Set.forEach()

2020-07-06 05:49发布

问题:

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.

回答1:

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?



回答2:

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();


回答3:

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.