0

在我的插件代码中,我创建了一个“设备”数组并将其返回给 JavaScript。数组中的设备是 NPObject 的一个实例。可以成功创建数组,并且可以推入设备实例。但是,当 JavaScript 调用设备对象的属性时,会返回“未定义”值。

html代码是:

<html>
<head>
<title>Netscape Core Animation Movie Plug-In</title>
<script language="javascript" type="text/javascript">
function devicelist(){
    var plug=document.getElementById('plugin');
    var devices=plug.getDevice();
    var tab='<table>';

    for(var device in devices){
        tab+='<tr><td>'+device.name+'</td><td>'+device.address+'</td></tr>';
    }

    tab+='</table>';

    document.getElementById('pluginlist').innerHTML=tab;
}

</script>

</head>
<body>
<div>
<embed width="848" height="480" id="plugin" movieurl="http://movies.apple.com/media/us/ipad/2011/tours/apple-ipad2-feature-us-20110302_r848-9cie.mov" type="test/x-netscape-core-animation-movie-plugin"></embed>
<p>JavaScript Controller</p>
<button onclick="devicelist()">Devices </button>
<div id="pluginlist"></div>
</div>
</body>
</html>

我在调用插件对象的“getDevice”方法时创建了数组。

static bool mainNPObjectInvoke(NPObject *obj, NPIdentifier identifier, const NPVariant *args, uint32_t argCount, NPVariant *result)
{
    MainNPObject *mainObject = (MainNPObject *)obj;

    if (identifier == methodIdentifiers[METHOD_ID_GET_DEVICES])
    {
        NPObject *windowObj = NULL;
        browser->getvalue(mainObject->npp, NPNVWindowNPObject, &windowObj);

        NPVariant devices;
        NPIdentifier name = browser->getstringidentifier("Array");
        browser->invoke(mainObject->npp, windowObj, name, NULL, 0, &devices);

        for (int i = 0; i < 3; i++)
        {
            Device *device = [[Device alloc] init];
            device.name = [NSString stringWithFormat:@"device%.2d", i];
            device.address = @"127.0.0.1";
            NPObject *deviceObj = createDeviceNPObject(mainObject->npp, device);
            //browser->retainobject(deviceObj);

            NPVariant *arg = browser->memalloc(sizeof(NPVariant));
            OBJECT_TO_NPVARIANT(deviceObj, *arg);

            NPVariant result;
            browser->invoke(mainObject->npp, devices.value.objectValue, browser->getstringidentifier("push"), arg, 1, &result);
        }

        browser->retainobject(devices.value.objectValue);
        OBJECT_TO_NPVARIANT(devices.value.objectValue, *result);

        browser->releaseobject(windowObj);

        return true;
    }

    return false;
}

为了让 JavaScript 知道数组有 NPObject 的实例,我有什么特别要做的吗?

4

1 回答 1

1

看起来你在滥用for循环。for 循环将迭代对象原型链的所有键而不是值。这是正确的用法:

function devicelist(){
    var plug=document.getElementById('plugin');
    var devices=plug.getDevice(), device;
    var tab='<table>';

    for (var prop in devices) {
        if (devices.hasOwnProperty(prop)) {
            device = devices[prop];
            tab += '<tr><td>'+device.name+'</td><td>'+device.address+'</td></tr>';
        }
    }

    tab+='</table>';

    document.getElementById('pluginlist').innerHTML=tab;
}
于 2012-05-06T15:13:15.937 回答