PDA

View Full Version : Need help to create custom events for my components


Gauthier
06-18-2003, 11:00 AM
Hello,

I'm working on components that I want to have 3 events:
-onChange (when the data change)
-onValidate (when the data become valid)
-onUnValidate (when the data becomes unvalid)

I need to trigger these events according specific logic to the code inner each controls that implement these events. These events has to be handled outside of the component (in a parent component for example) the same way I handle events with traditionnal events.

ie:
myElm.onclick = function(){alert('you just clicked');}

myComponent.onChange = function(){}

I want if it's possible to obtain a reference of the component that trigger the event to be accessible in the event handler code. I wonder if the keyword 'this' will have this behavior in the event handler code?

is it possible to do this kind of development with Javascript? (it has to work with IE5+ and Mozilla 1+)

Does anyone that know how to do will show me the right syntax?

Thanks alot for your assistance.

jkd
06-18-2003, 05:48 PM
In Gecko, you can do:

var event = document.createEvent("Events");
event.initEvent("validate", canBubble, isCancelable);
someElement.dispatchEvent(event);

Where canBubble is a boolean reflecting whether you want the event to bubble, isCancelable is a boolean reflecting whether you can cancel the event, and someElement is the deepest node you want to receive the event.

To pick up on the event, you'd just do:

someElement.addEventListener("validate", function(event) { /* my listener */ }, false);


This is pure DOM2 Events stuff, and custom events are actually implied by the specification:

Any new event type must not begin with any upper, lower, or mixed case version of the string "DOM". This prefix is reserved for future DOM event sets. It is also strongly recommended that third parties adding their own events use their own prefix to avoid confusion and lessen the probability of conflicts with other new events.


Of course, IE doesn't support DOM2, so you're out of luck with that. You can do custom events through some obfusticated scriptlet process, but I've looked into it before and is rarely useful.
(fireEvent() throws errors on unknown events as well)

And I don't seem to remember Opera 7 supporting this, though you could give it a try.


The alternative is to enforce your own events system:

someElement.onvalidate = function() { blabla }


......
// validate(someElement)
someElement.onvalidate();

Gauthier
06-20-2003, 03:03 PM
Hello,

Many thanks for your insight, you described me the standard way of creating event very well :)

I've also find the dom_drag.js (on http://youngpup.net) that will help me to manage the weak way of adding events to my components.

By the way, can you tell me something on this library if you have allready used it?
http://www.doxdesk.com/software/js/event.html

Thanks again