Search code examples
javascriptc#activexactivexobject

ActiveX Event and Javascript Callaback Reigstration


i've developed a c# Library, registered as COM component. Now i need to import the ActiveX created into a html page with Javascript to use the ActiveX function. All is fine except for Callback, probably i lack in knowledge in Javascript but i'm still not able to use properly Callback. I've searched many example but some are too much deep for my objective and other one can't clear the point, so here the question.

I will explain myself:

Thi is the Event in the ActiveX component

public delegate void ButtonEvent(object sender, SignEventArgs e);
public event ButtonEvent ButtonSignOk;

This is the snippet of my Javascript

try {
    var Lib = new ActiveXObject("AGI.GraphometricLib");
    Lib.Initializer();
    Lib.addEventListener('ButtonSignOk', OnOkHandler, false);
    } catch (ex) {
        alert("Error: " + ex.message);
    }

function OnOkHandler(arg1, arg2){
    alert("Pressed!");
}

Obviously the addEventListener return an error.

Error: Object doesn't support property or method 'addEventListener'

How can i properly setup a javascript callback for that event defined in the ActiveX ?


Solution

  • Event handlers for ActiveX objects can be written with the following syntax:

    function Lib::ButtonSignOk(sender, e)  {
        alert("Pressed!");
    }
    

    However, there is a catch. The nature of Javascript is that

    1. function declarations are evaluated before anything else in the file
    2. this function declaration is interpreted as adding an event handler to the object referred to by Lib, which doesn't exist at the beginning of the file.

    The solution is to force the function declaration to be evaluated after the variable initialization, e.g.:

    var Lib = new ActiveXObject("AGI.GraphometricLib");
    Lib.Initializer();
    
    (function() {
        function Lib::ButtonSignOk(sender, e) {
            alert('Pressed!');
        }
    })();
    

    See here for a full writeup, and here for a library I've written that makes this a little easier.