0

I have a widget that insert a div element in the DOM; that div needs some js that handles the resize event;

the problem is:

  • the widget can be added multiple times on the same page, but I don't wanto to add many identical resize event handlers on the page (one, acting on the specific widget's class will be enough for all the widget instances);

  • the page that will embeed the widget can have its own resize event handler, that should not be deleted;

do you have any suggestion about how to implement this?

Cereal Killer
  • 3,387
  • 10
  • 48
  • 80
  • 1
    [Namespace your widget's event handler](http://www.learningjquery.com/2007/09/namespace-your-events), then [check if that event handler exists](http://stackoverflow.com/questions/976343/how-can-i-check-if-a-javascript-eventhandler-has-been-set) before adding a new one. – Blazemonger Jan 04 '16 at 18:37
  • 1
    The desired outcome is not well define in your question - but if you want to limit a listener to a single instance, but be able to retrieve that instance whenever you would like - you can use a singleton that create a handler on an object and then just passes you back a reference to the object with its handler (and it's props and methods) instead of creating a new one when you call the singleton method. – Korgrue Jan 04 '16 at 18:51

1 Answers1

1

Honestly, I didn't get most of workflow explained as you didn't provide any html and js but I hope the following works for you:

var resized = 0;                     // works as a flag
$( window ).on('resize', function () { 
     if ( resized++ >= 1 ) return;
     // do something here.. 
     console.log('resized once');    // console.log as an example! 
});

Good luck.

KQI
  • 322
  • 1
  • 16