Join the Stack Overflow Community
Stack Overflow is a community of 6.6 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

I've got a section on my page where there's a couple of blocks. When loading this page, I create an array blocks[] that stores a block object for each one, these contain some more information on the blocks.

function block(info, DOM) {
    this.id = info["id"];
    this.DOM = DOM;
    this.title = info["title"];
    this.icon = info["icon"];
    this.author = info["author"];
}

The DOM field holds the with the object associated block. Now, I'm trying to figure out the best way to get hold of my block object when you click the block.

$(".block").click(..)

I'm currently thinking of using the above ^ and then using the index of the clicked element to get the block object out of the blocks[] array, but I'm left wondering if there would be some way to link it more directly with the .DOM field in Block, like having a specific click trigger in the block class. Is there a cleaner way like that to do it or should I just use the index? Thanks in advance!

share|improve this question
    
if you want create (and pass) also a this.$DOM which will be the jQuery element object. Than you can do referee.$DOM.click() – Roko C. Buljan 42 mins ago

Yes, that is Indeed a way of doing.

However, instead of attaching event handlers for each block as shown below

$(".block").click(function(e){
  // do event handling
});

you could try event delegation as shown below

you can use event delegation

var blocks=[{},{},{}];

$("parent_for_blocks").on('click', '.block', function(e){
  // do event handling
  var index = $(this).index();
  console.log(blocks[index]);  // returns clicked block information
});
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.