Javascript:使用new关键字创建的函数对象内的事件

时间:2012-11-12 17:22:05

标签: javascript events object com activexobject

我有一个C#COM DLL(“This.That”)有事件,我用JS测试过,它们工作正常。我现在正试图将所有经过测试的代码包装在一个对象中。以下示例正常工作:

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;
        }
    };
}

但是一旦我尝试向它添加一个事件,它就不起作用了。看起来它可能是糟糕的语法。我找不到任何在线资源来解释这是如何完成的。

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";
    };
}

1 个答案:

答案 0 :(得分:0)

我已经有了一些工作,但我仍然希望看到其他答案。这会将事件处理程序放在JS文件之外并放入文档中,但代码本身仍然在JS文件中。代码的组织是我最关心的问题,所以这对我来说是可以接受的。

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);
    };
}