0

I am trying to use JQuery events in typescript, but they seem to fire at the time the the event handler is declared instead of when the event is fired. Here's some code:

function button(buttonName){
    var buttonDiv = loadNewDivFromTopLeft(rootID, 45, 120, 560, 440, "blue-button", 110);
    loadSpan(buttonDiv, buttonName, "button-font");
    $(idSelector(buttonDiv)).click(alert("Hello"));
}

In this code, a button is being created. A div is created as a button and then a span with text is added to it. Then I am trying to add an alert message to when the button (div) is clicked on. This function should create an alert when the button is clicked on, but it creates an alert when the button is rendered - which is when the "function button" is called - instead of when the button is clicked on.

I got the typescript version of jQuery from this page: http://typescript.codeplex.com/sourcecontrol/latest#samples/jquery/jquery.d.ts

I am using the tsc compiler in webstorm to compile. However, assuming that any javascript is valid typescript I also got the original javascript code and pasted it in the .d.ts file. But that gave a compilation error too. Please advise.

2 Answers 2

2

What you're doing wrong is calling the function when you pass it as an argument to the 'Click' method of the element. Like this...

$(idSelector(buttonDiv)).click(alert("Hello"));

This will fire when you declare the click method. What you want to do is to pass a method which calls the 'alert' method, as an argument to the 'click' declaration, like this.

$(idSelector(buttonDiv)).click(function(){alert("Hello");});

This will work as you expect it to.

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

Comments

1

You need to pass a function reference as the parameter to click(). In your case you are invoking the alert() method and passing the value returned by it(undefined) as the value to the click handler.

Use a anonymous function as the click handler inside which you can add the alert() as given below

$(idSelector(buttonDiv)).click(function(){
    alert("Hello")
});

Comments

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.