Passing parameters to addEventListener

I am working on a Firefox extension and I am trying to pass the addEventListener parameter. I am “listening” to the changes in the page title, my code looks something like this:

function Test() { this.checkTitle = function( event ) { var func = function() { this.onTitleChange ( event ); }; var target = content.document.getElementsByTagName('TITLE')[0]; target.addEventListener('DOMSubtreeModified', func, false); } this.onTitleChange = function( e ) { // do stuff with e alert('test'); } this.handleEvent = function (event) { switch (event.type) { case "DOMContentLoaded": { this.checkTitle( event ); } } } window.addEventListener ("DOMContentLoaded", this, false); } 

I never get a "test" warning if I use func = function () {alert (event); }; it shows a warning with "[object Event]". Also tried without using this. on func but still not working.

How can I make this work have access to the checkTitle "event" parameter in onTitleChange?

+4
source share
1 answer

When the browser calls the event handler, this will refer to this element, not your instance.

You need to save a copy of the desired this in a separate variable:

 var self = this; var func = function(e) { self.onTitleChange (e); }; var target = content.document.getElementsByTagName('TITLE')[0]; target.addEventListener('DOMSubtreeModified', func, false); 
+3
source

All Articles