Skip to content

addEventListener as |this| #216

@paulushub

Description

@paulushub

This sample is found on the Mozilla site: addEventListener

const Something = function(element) {
  // |this| is a newly created object
  this.name = 'Something Good';
  this.handleEvent = function(event) {
    console.log(this.name); // 'Something Good', as this is bound to newly created object
    switch(event.type) {
      case 'click':
        // some code here...
        break;
      case 'dblclick':
        // some code here...
        break;
    }
  };

  // Note that the listeners in this case are |this|, not this.handleEvent
  element.addEventListener('click', this, false);
  element.addEventListener('dblclick', this, false);

  // You can properly remove the listeners
  element.removeEventListener('click', this, false);
  element.removeEventListener('dblclick', this, false);
}
const s = new Something(window); // changed document.body to window for the demo

Defining a window object in C# as follows, I received the call to the addEventListener method.

public class JsSvgWindowNiL {
    public void addEventListener(string type, object listener, bool useCapture) {
        Trace.WriteLine("addEventListener(string type, object listener, bool useCapture)");

        Function listenerFunc = null;
        var listenerValue = listener as JSValue;
        if (listenerValue != null) {
            listenerFunc = listenerValue.Value as Function;
        }
    }
}

However, for the above script, the listenerValue.Value is JSObject (not Function as in all other cases). How do I invoke/call the JS handler in this case?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions