0

A few weeks ago I was painfully able to dynamically add buttons to an HTML DOM object that has its own .on('click'.. handler, and use e.stopPropgation to stop these new child elements from firing the event.

The weird thing I did was call a function without any parenthesis. I have no idea why I did this or why it works, or why it does not work when I do attach parenthesis. I want to know if I am doing something by fluke and not design (and now I will add comments to it).

It goes as such:

//Container is the parent element
// var buttons stores the buttons with class 'buttons'
$('.container').on('click', function(){
    $(buttons).appendTo($(this)).fadeIn(500).find('.buttons').click(tableButton);
});

function tableButton(e){
    e.stopPropagation();
    //do stuff

}

I can't figure out why I wrote the call to tableButton with no arguements or why it works perfectly. I tried to change the syntax to

.find('.buttons').on('click', function(e){
  tableButton(e);
});

but then it no longer works.

Any help appreciated!

0

2 Answers 2

1

It works because you're passing a function to the click handler rather than calling the function yourself (the ()) An example of that:

var testFunction = function(msg) {
    alert(msg);
}

var functionCaller = function(functionToCall) {
    functionToCall('hello!');
}

functionCaller(testFunction);

functionCaller passes the message argument to testFunction(), but we only pass testFunction to functionCaller (without arguments)

For the part which doesn't work, isn't the function name tableButton() instead of tableButtons()?

See http://jsfiddle.net/g2PAn/

Sign up to request clarification or add additional context in comments.

2 Comments

This seems like a really complex way to do things. Is there any reason for it?
Yes. It's so you can use your function as a delegate. For example you can use your same click handler and attach it to multiple click events.
1

You don't actually call it, you just declare it and the arguments it accepts. The click callback is called with an argument indeed, but not by you.

The problem probably comes from the fact that jQuery calls your function with the element clicked bound as this, you could call table button like this:

.find('.buttons').on('click', function(e){
     tableButton.call(this, e);
});

1 Comment

So what do you mean, called with an arguement but not by me? Is this invalid or improper syntax?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.