What I want to have is a custom object which provides some events.
For example:
var CustomObjectTextChangedEventName = 'textChanged';
var CustomObject = function () {
var _this = this;
var _text = "";
_this.OnTextChanged = document.createEvent("Event");
_this.OnTextChanged.initEvent(CustomObjectTextChangedEventName, true, false);
_this.ChangeText = function (newText) {
_text = newText;
fireTextChanged();
};
function fireTextChanged() {
_this.dispatchEvent(_this.OnTextChanged);
}
}
The code to use the event would look like:
myCustomObject = new CustomObject();
myCustomObject.addEventListener(CustomObjectTextChangedEventName, handleTextChanged, false);
As you can see… the default way of using events in JS, but I can not make it work…
Currently my problem is that my object does not implement addEventListener and dispatchEvent, but this functions are normally implemented from "element"…
Can I make them available somehow or do I have to implement them for my own?
How I have to implement them?
Do I have to implement my own event handling? (having a internal list of handlers, an "add"- and "remove"-handler function, and fire each handler when I want to fire the event)?
The
addEventListenerfunction is a method ofElementclass. One way is to makeCustomObjectinherit fromElementlike this:The problem is that
Elementclass may have different implementations among different browsers. So for example firing events may not be easy (see this post).So I advice doing this by yourself. It is not difficult, try something like this:
Now using it is as simple as:
This is a basic solution. You may want to alter it, but I think you should grasp the idea.