Amol Pujari
Amol Pujari

Reputation: 2349

avoid repeating jquery event bindings

I got into a situation where some of the page contents are partially getting loaded in ajax, and that adds one compiled js including jquery_ujs, which then repeats all ujs events, like for instance when you click on delete you get confirmation, its getting repeated.

Hence wanted to know how to avoid repeating of event binding by any trick and not ensuring js is not re-reloaded in general. Or is there any flag or control in ujs, I did not find though, we could achieve this, so re-load ujs any time but get event binding only once.

hmm...Why not event binding is idempotent?

Is there any solution apart from keeping apart such js files and ensuring they get loaded only once?

And btw, is there any tool which detects such repeated bindings?

Upvotes: 0

Views: 2023

Answers (4)

Billy Chan
Billy Chan

Reputation: 24815

If you find garbage in house, will you clean it or decorate it?

It's your duty to make sure no unnecessary js loaded. Just as simple as that.

Upvotes: 1

gokul
gokul

Reputation: 393

There is something known as Self*-Defining Functions* in Javascript. This pattern is useful when your function has some initial prepatory work to do and it needs to do it only once. In such case, the self-defining function can update its own implementation.

For e.g

var shout= function(){
    alert('shout!');
    shout= function(){
          alert('shout again');
   }
}

//using self-defining function
shout(); // shout!
shout(); // shout again!

Hope this would be useful to you.

Upvotes: 0

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

Something like this?

$(selector).on('click',function(){
  //do stuff here
  $(this).off('click');
});

Or you can use something like this:

var clicked = false;
$(selector).on('click',function(){
  if(!clicked){
  clicked = true;
  //do stuff here

  .....somefunc(){
  clicked = false;
  }
  ...
  }
});

Upvotes: 0

Neil Cresswell
Neil Cresswell

Reputation: 1165

Although you should use a cleaner method, sometimes when you're working on someone else's code and just need a quick fix to ensure an event isn't set up more than once (with nebulous code) then I've done this:

$(someSelector).off('click').on('click', function(event)
{
    // whatever
});

Upvotes: 2

Related Questions