views:

105

answers:

2

HI,

I've trying to listen for events fried by my ATL object. I find that if I include a script as follows directly in the HTML of the page it picks up the event correctly.

<html>
<head>
<script event="genericScriptEvent(param0, param1, param2, param3, param4, param5,    param6, param7, param8)" for="CMyControl" type="text/javascript">
<.head>
...
</html>

However, I'm now creating the html page dynamically and just need to inject the script fragment into the head tag. I've coded up the following method, there are no errors, but it doesn't raise any events once the control is on the page.

function loadJavascriptEventHandler(element, filePath, objectName, callbackFunction)
{
    var head = element.doc.getElementsByTagName("head")[0];  
    var tag = element.doc.createElement('script'); 
    tag.setAttribute('type', 'text/javascript'); 
    tag.setAttribute('src', filePath );
    tag.setAttribute('for', objectName );
    tag.setAttribute('event', callbackFunction );
    head.appendChild(tag);

}

Where "filepath" just contains "genericScriptEvent(param0, param1, param2, param3, param4, param5, param6, param7, param8)"

Is there some dependency on when the script must exist in the page load cycle? (the object is always created after the script tag is added). How else can i dynamically add the event listener script? This problem occurs in IE7.

A: 

Don't use setAttribute on an HTML document. It has many bugs in IE and is generally much less readable than just using the direct DOM Level 1 HTML properties:

tag.src= filePath;

However, I'm not sure inserting one of IE's weird script for elements into the DOM actually works. Maybe it does, maybe it doesn't, but it's pretty ugly. Would attachEvent not be better?

var obj= document.getElementById(objectName);
obj.attachEvent('genericScriptEvent', function(param0, param1) {
    ...
});
bobince
A: 

I don't use ATL objects, but the following works great for me with vb6/.net user controls and classes:

function CMyControl::EventName () { //...Event handling code... }

As mentioned by bobince, setAttribute in IE is buggy, particularly with "for" attribute, which expects the DOM property equivalent instead, which is "htmlFor".

Andy E