Skip to content
Advertisement

Detach event handlers selectively

I have a html richText editor. My code structure is like this:

function richTextEditor(div)
{

   var self=this;
   self.instanceIdentifier=Math.floor(Date.now());
   //Richtext editor creation logic 
    
   $(document).on('click.'+self.instanceIdentifier,function()
    {
      //some logic
    })

   self.destroy=function()
   { 
     //delete all properties of self
     // detach all listeners
     $(document).off('click.'+self.instanceIdentifier) ;
   }
}

Our app is single page application, and there are multiple richtexteditor instances opened in different panes. I need to destroy the instance when the node corresponding to this has been removed. Destroy should remove all the event handlers attached by that instance.

So far Date.now() for uniquely identifying the handler is working but I think there must be some elegant way to do that.

   var div1=$('#notes')[0];
   var editorInstance1=new richTextEditor(div1);
   //remove is not a valid jquery event, its just for illustration
   // I am getting remove event from another library
   $(div1).on('remove',function(){
       editorInstance1.destroy();
    })

Please suggest if this is the correct way to go.

Advertisement

Answer

What you want is a GUID or UUID. There is a great answer to this question here.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement