开发者

Passing parameters in addEventListener

开发者 https://www.devze.com 2023-01-25 04:10 出处:网络
I am working on a Firefox extension, and I am trying to pass a parameter to addEventListener. I am \"listening\" for changes in the page title, my code looks something like this:

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

function Test()
{
    this.checkTitle = function( event )
    {
        va开发者_如何学Cr 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 the 'test' alert, if I use func = function() { alert(event); }; it does show an alert with '[object Event]'. Also tried without using this. on func but still wont work.

How can I make this work to be able to access checkTitle parameter "event" into onTitleChange?


When the browser calls the event handler, this will refer to the 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);
0

精彩评论

暂无评论...
验证码 换一张
取 消