Question

a = new object();
a.loadInterface();

$("button").click(function() {
    a.doSomething();
});

The problem is that a.loadInterface() is what loads the button into the DOM, and it happens at the end of a $.post() because data from the server is needed to populate some attributes of the button.

So what I think is going on is, JavaScript reads the button.click detector but at that time there is no button for it to bind to.

Any ideas?

Was it helpful?

Solution

Your assessment of the problem is correct. A simple solution would be to use delegate. E.g.,

$(document).delegate('button', 'click', function() {
    a.doSomething();
});


Edit: more info on delegate and why it works on dynamically created elements after event binding can be found here: http://api.jquery.com/delegate/

OTHER TIPS

I think you are right. If you are creating button in based on the data returned from the post, you'll need to bind event in the method that is executed after the success of the post.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top