Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Daniel Maia
2,559 PointsSame function for multiple variables in an array; how to?
So I have an array with some variables. I want to define a function to be called every time an specific event happens over the variables. The function is the same for all.
Of course a simple solution would be to go one by one manually and do something as:
array[0].onevent = doThis();
array[1].onevent = doThis();
array[2].onevent = doThis();
/*and there it goes ...*/
But let's say that this will take a lot of work and the quantity of variables inside this array may vary, but all these variables share the same event and I want them as well to share the same function when this event happens.
I tried doing a for loop like:
for (item in array){
item.onevent = doThis();
}
... but that only calls the function once for each item inside the array independently from the event.
Anyway, how can I reach a practical and efficient way to define a function for each variables event.
2 Answers
Colton Ehrman
Courses Plus Student 5,859 PointsHmmm not sure if this will help but check out http://www.kirupa.com/html5/handling_events_for_many_elements.htm
Colton Ehrman
Courses Plus Student 5,859 PointsInteresting problem, perhaps you could show me a little bit of your code to see the context of your problem?
Daniel Maia
2,559 PointsAhmm... Sure, it's right here: http://codepen.io/bakedCookie/pen/XbeYvO; So that's more complex, since it's the REAL code; I mean, it's where I'm trying to apply this.
Daniel Maia
2,559 PointsDaniel Maia
2,559 PointsThat's a lot of things for me to study, but thanks. I'm learning a lot with that. I still didn't reach the answer to my problem, but that article is being very useful since I'm covering some basics I didn't know about events.