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.
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...
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.
This will work as you expect it to.