简体   繁体   中英

Javascript: Event inside a function object created with the new keyword

I have a C# COM DLL ("This.That") that has events, which I've tested using JS and they work fine. I'm now trying to wrap all my tested code inside an object. The following example works fine:

var oTest = new Test();

function Test()
{
    var oDevice = new ActiveXObject("This.That");

    this.CancelOperation = function()
    {
        try
        {
            oDevice.CancelOperation();
            return "CancelOperation successful.";
        }
        catch (e)
        {
            return e.message;
        }
    };
}

But once I try to add an event to it, it doesn't work. It looks like it's probably bad syntax. I can't find any resources online that explain how this is done.

var oTest = new Test();

function Test()
{
    var oDevice = new ActiveXObject("This.That");

    this.CancelOperation = function()
    {
        try
        {
            oDevice.CancelOperation();
            return "CancelOperation successful.";
        }
        catch (e)
        {
            return e.message;
        }
    };

    oDevice::DeviceStatusUpdate(wasSuccess, message, data) = function()
    {
        document.getElementById("outBox").value += "Success: " + wasSuccess.toString() + "\nMessage: " + message + "\nData:" + data + "\n\n";
    };
}

I've gotten something working but I'd still like to see other answers. This puts the event handler outside of the JS file and into the document, but the code itself is still inside the JS file. The organization of the code was my greatest concern so this is acceptable to me.

var oTest = new Test();

function Test()
{
    var oDevice = new ActiveXObject("This.That");

    this.CancelOperation = function()
    {
        try
        {
            oDevice.CancelOperation();
            return "CancelOperation successful.";
        }
        catch (e)
        {
            return e.message;
        }
    };

    this.WireEvents = function()
    {
        var script = document.createElement("script");
        script.type = "text/javascript";
        script.text = 'function oTest.oDevice::DeviceStatusUpdate(wasSuccess, message, data) { document.getElementById("outBox").value += "Success: " + wasSuccess.toString() + "\\nMessage: " + message + "\\nData:" + data + "\\n\\n"; }';
        document.body.appendChild(script);
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM