Link to home
Start Free TrialLog in
Avatar of DuNuNuBatman
DuNuNuBatman

asked on

Creating and Raising Custom Events

I'm writing a javascript wrapper for a com object I wrote. I'm not able to expose the com events directly so instead I'm using setInterval to check the status of a property in the com object. My goal is to allow the user to use my library to respond to the event fired by the "class" I created. I'm not sure how you can declare custom events in my "class" to be used by the end user.

Here is what I'm looking to do for the user. This is code he would write to use my event:

var myObj = new TestObj();
myObj.OnStatusTrue += DoStuff;

function DoStuff(filesChanged)
{
    // This does stuff with filesChanged
}

Here's an example of the class I created:
function TestObj()
{
    // Declare the event?

    var comObj = ActiveXObject("Namespace.Class");

    setInterval("CheckForTrue()", 1000);

    function CheckForTrue()
    {
        if (comObj.IsPropertyTrue)
        {
            // Fire the event
            // This will cause the clients method to fire above
        }
    }
}

Anyway, that's what I'm trying to accomplish. If there are errors in the above code, I'm sorry. I just wrote that as an example and I haven't touched javascript in a long time.
Avatar of Göran Andersson
Göran Andersson
Flag of Sweden image

There are two problems with the code:

1. You have declared the CheckForTrue function inside another function. Move it outside.

2. You have declared the comObj variable locally in the TestObj function, which means that it doesn't exist any more once the function ends. Declare the variable outside the function.
Avatar of DuNuNuBatman
DuNuNuBatman

ASKER

No, that's all correct. I was trying to figure out how to call custom created events in javascript. I figured it out.
ASKER CERTIFIED SOLUTION
Avatar of Göran Andersson
Göran Andersson
Flag of Sweden image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
// Fixed
setInterval(CheckForTrue, 1000);
Force accepted.
modus_operandi
EE Moderator