1

I would like to return the unique name of the object that the user has clicked on but I can't find the solution. Below is what I'm trying to achieve but in CoffeeScript.

$(".class").click(function(){
    alert("You clicked on this specific element");
});

The best example I could find is shown below, but each layer is unique so they can't be assigned to different layers.

layerA.on Events.Click, (event, layer) ->
    print "This layer was clicked", layer.name

I can listen to the event on each layer individually, but that would breach the DRY principle.

Raja
  • 369
  • 2
  • 5
  • 18

2 Answers2

1

I've managed to figure it out myself. Here's the solution below.

Create an array and store all of the layer names inside

layerArray = [layer, layer2, layer3, layer4]

Create a function that will be called when the click event is triggered, passing in the layer object and the layer index

callFunc = (layer, index) ->
    print index

Loop over each layer in the array and pass the clicked layer to the function

for layer, index in layerArray
    layer.on(Events.Click, callFunc)
Raja
  • 369
  • 2
  • 5
  • 18
0
$(".class").click(function(e){
    alert(e.target); // The DOM element that fired this event.
});

See https://api.jquery.com/click/#click-handler specifically

.click( handler )
handler Type: Function( Event eventObject )
A function to execute each time the event is triggered.

And http://api.jquery.com/category/events/event-object/

event.target
The DOM element that initiated the event.

David Waters
  • 11,979
  • 7
  • 41
  • 76
  • Hey David, thanks for your answer. I managed to figure it out myself earlier and i ended up writing an answer for others to see, just in case they had the same issue. It's a Framer.js question and it uses coffeescript. I'm new to it myself and realised that I had to loop over the array values to get the specific index that was clicked. jQuery does it slightly differently. Anyways, thanks again for your help! – Raja Apr 13 '15 at 03:05