user3822370
user3822370

Reputation: 647

Should event handlers be added dynamically or on document ready?

Currently I use two methods of adding event handlers to dynamically added DOM objects, reason being I don't know which makes more sense.

Method 1 - with creation

function createButton(){
   var btn = $('<div class = "btn"/>');
   btn.on('click', function(){
     doStuff();
   });
   $('body').append(btn);
}

Method 2 - on document ready

function createButton(){
   var btn = $('<div class = "btn"/>');
   $('body').append(btn);
}

$('document').on('ready', function(){
   $('body').on('click', '.btn', function(){
     doStuff();
   });
});

I have long running app considerations as well, and would be concerned about garbage collection issues here.

Upvotes: 0

Views: 37

Answers (1)

ShaharZ
ShaharZ

Reputation: 389

In Method 1 you're attaching a new, although not unique handler object to each button you create.

In Method 2 you're reusing the same handler object for anything with the .btn class.

In the short term, I'd use Method 2 because you only have 1 handler function for any given button, so you might as well save memory by not creating redundant handlers.

Upvotes: 1

Related Questions