RaphaelJS Set.forEach()

青春壹個敷衍的年華 提交于 2019-12-21 07:57:12

问题


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.


来源:https://stackoverflow.com/questions/9034714/raphaeljs-set-foreach

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!