11

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)?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Dominik Kirschenhofer
  • 1,205
  • 1
  • 13
  • 27
  • I don;t know if this helps but Backbone.js has events built into them. Every model created using it can trigger custom events using syntax `object.trigger(event_name)` – Deeptechtons Jun 11 '12 at 11:37
  • It is also easy with jQuery... thats why I tought it can not be that hard :P $(_this).trigger(CustomObjectTextChangedEventName, _text); $(myCustomObject).bind(CustomObjectTextChangedEventName, handleTextChanged); – Dominik Kirschenhofer Jun 11 '12 at 11:50

4 Answers4

20

The addEventListener function is a method of Element class. One way is to make CustomObject inherit from Element like this:

CustomObject.prototype = Element.prototype;

The problem is that Element class 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:

var CustomObject = function () {
    var _this = this;
    _this.events = {};

    _this.addEventListener = function(name, handler) {
        if (_this.events.hasOwnProperty(name))
            _this.events[name].push(handler);
        else
            _this.events[name] = [handler];
    };

    _this.removeEventListener = function(name, handler) {
        /* This is a bit tricky, because how would you identify functions?
           This simple solution should work if you pass THE SAME handler. */
        if (!_this.events.hasOwnProperty(name))
            return;

        var index = _this.events[name].indexOf(handler);
        if (index != -1)
            _this.events[name].splice(index, 1);
    };

    _this.fireEvent = function(name, args) {
        if (!_this.events.hasOwnProperty(name))
            return;

        if (!args || !args.length)
            args = [];

        var evs = _this.events[name], l = evs.length;
        for (var i = 0; i < l; i++) {
            evs[i].apply(null, args);
        }
    };
}

Now using it is as simple as:

var co = new CustomObject();
co.addEventListener('textChange', function(name) {
    console.log(name); 
});
co.fireEvent('textChange', ['test']);

This is a basic solution. You may want to alter it, but I think you should grasp the idea.

Community
  • 1
  • 1
freakish
  • 54,167
  • 9
  • 132
  • 169
  • That is what I have ment with "having a internal list of handlers, an "add"- and "remove"-handler function, and fire each handler when I want to fire the event" =) Thank you! – Dominik Kirschenhofer Jun 11 '12 at 11:38
  • @DominikKirschenhofer Cool. I forgot about `remove` handler, so I've just added it. It should work. :) – freakish Jun 11 '12 at 11:53
  • 1
    Regarding the "tricky" part - removing handlers by passing the same function object: the same is true for native event handlers. I just tested a buttons `click` event, and `removeEventListener` did not work unless I provided a reference to the same function object. – Cristian Lupascu May 24 '15 at 18:44
  • Freakish, why did you use `var _this = this` in the beginning? – The Onin Sep 04 '17 at 02:44
  • Oh, nvm, because you wanted to use it within child functions, where `this` would've been redeclared. – The Onin Sep 04 '17 at 02:46
1

I'm not sure on all 100% but next is a result of my old research within this problem:

  • You cannot make available somehow this.
  • You can simply implement your own logic. For this you can use code that exist in MDN element.removeEventListener article with little changes. Below it copy\past of code from MDN link:

// code source: MDN: https://developer.mozilla.org/en/DOM/element.removeEventListener
// without changes
if (!Element.prototype.addEventListener) {  
  var oListeners = {};  
  function runListeners(oEvent) {  
    if (!oEvent) { oEvent = window.event; }  
    for (var iLstId = 0, iElId = 0, oEvtListeners = oListeners[oEvent.type]; iElId < oEvtListeners.aEls.length; iElId++) {  
      if (oEvtListeners.aEls[iElId] === this) {  
        for (iLstId; iLstId < oEvtListeners.aEvts[iElId].length; iLstId++) { oEvtListeners.aEvts[iElId][iLstId].call(this, oEvent); }  
        break;  
      }  
    }  
  }  
  Element.prototype.addEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {  
    if (oListeners.hasOwnProperty(sEventType)) {  
      var oEvtListeners = oListeners[sEventType];  
      for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {  
        if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }  
      }  
      if (nElIdx === -1) {  
        oEvtListeners.aEls.push(this);  
        oEvtListeners.aEvts.push([fListener]);  
        this["on" + sEventType] = runListeners;  
      } else {  
        var aElListeners = oEvtListeners.aEvts[nElIdx];  
        if (this["on" + sEventType] !== runListeners) {  
          aElListeners.splice(0);  
          this["on" + sEventType] = runListeners;  
        }  
        for (var iLstId = 0; iLstId < aElListeners.length; iLstId++) {  
          if (aElListeners[iLstId] === fListener) { return; }  
        }       
        aElListeners.push(fListener);  
      }  
    } else {  
      oListeners[sEventType] = { aEls: [this], aEvts: [ [fListener] ] };  
      this["on" + sEventType] = runListeners;  
    }  
  };  
  Element.prototype.removeEventListener = function (sEventType, fListener /*, useCapture (will be ignored!) */) {  
    if (!oListeners.hasOwnProperty(sEventType)) { return; }  
    var oEvtListeners = oListeners[sEventType];  
    for (var nElIdx = -1, iElId = 0; iElId < oEvtListeners.aEls.length; iElId++) {  
      if (oEvtListeners.aEls[iElId] === this) { nElIdx = iElId; break; }  
    }  
    if (nElIdx === -1) { return; }  
    for (var iLstId = 0, aElListeners = oEvtListeners.aEvts[nElIdx]; iLstId < aElListeners.length; iLstId++) {  
      if (aElListeners[iLstId] === fListener) { aElListeners.splice(iLstId, 1); }  
    }  
  };  
}  
  • I think what all you need to change is to replace Element.prototype with CustomObject.prototype. And for supporting dispathEvent you must add CustomObject.prototype.dispatchEvent = runListener; code line. Also is can be better to enclose this code into closure function;

I don't tested this in my apps but maybe this can help you.

UPDATE: Next link points into code source that contains XObject() class that supports event adding/removing and dispatching events. Test example is included. All code is based on answer above. http://jsfiddle.net/8jZrR/

Andrew D.
  • 8,130
  • 3
  • 21
  • 23
1

I have improved my sample with the code from freakish. I still would extract the eventhandling part into a "base class"... maybe when there is some more time =)

There is also a sample for using jQuery!

<!doctype html>
<html lang="en">
<head>    
    <title>Custom Events Test</title>    
    <meta charset="utf-8">    
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>    
    <script>
        /* jQuery

        var CustomObjectTextChangedEventName = 'textChanged';
        var CustomObject = function () {
            var _this = this;
            var _text = "";

            _this.ChangeText = function (newText) {
                _text = newText;
                fireTextChanged();
            };

            function fireTextChanged() {
                $(_this).trigger(CustomObjectTextChangedEventName, _text);
            }
        }

        var myCustomObject;
        $(document).ready(function () {
            myCustomObject = new CustomObject();
            $(myCustomObject).bind(CustomObjectTextChangedEventName, handleTextChanged);
        })

        function handleTextChanged(event, msg) {
            window.alert(msg);
        }

        function buttonClick() {
            var newText = document.getElementById('tbText').value;

            myCustomObject.ChangeText(newText);
        }

        */


        var CustomObjectTextChangedEventName = 'textChanged';
        var CustomObject = function (alias) {
            var _this = this;
            var _events = {};
            var _text = "";

            _this.Alias = alias;

            _this.OnTextChanged = document.createEvent("Event");
            _this.OnTextChanged.initEvent(CustomObjectTextChangedEventName, true, false);

            _this.ChangeText = function (newText) {
                var args = new TextChangedEventArgs();
                args.OldText = _text;
                args.NewText = newText;

                _text = newText;
                fireEvent(CustomObjectTextChangedEventName, args);
            };

            _this.addEventListener = function (name, handler) {
                if (_events.hasOwnProperty(name))
                    _events[name].push(handler);
                else
                    _events[name] = [handler];
            };

            _this.removeEventListener = function (name, handler) {
                /* This is a bit tricky, because how would you identify functions? 
                This simple solution should work if you pass THE SAME handler. */
                if (!_events.hasOwnProperty(name))
                    return;

                var index = _events[name].indexOf(handler);
                if (index != -1)
                    _events[name].splice(index, 1);
            };

            function fireEvent(name, args) {
                if (!_events.hasOwnProperty(name))
                    return;

                var evs = _events[name], l = evs.length;
                for (var i = 0; i < l; i++) {
                    evs[i](_this, args);
                }
            }
        }

        var TextChangedEventArgs = function () {
            var _this = this;

            _this.OldText = null;
            _this.NewText = null;
        }

        var myCustomObject;
        var myCustomObject2;
        window.onload = function () {
            myCustomObject = new CustomObject("myCustomObject");
            myCustomObject.addEventListener(CustomObjectTextChangedEventName, handleTextChanged);

            myCustomObject2 = new CustomObject("myCustomObject2");
            myCustomObject2.addEventListener(CustomObjectTextChangedEventName, handleTextChanged);
        };

        function handleTextChanged(sender, args) {
            window.alert('At ' + sender.Alias + ' from [' + args.OldText + '] to [' + args.NewText + ']');
        }

        function buttonClick() {
            var newText = document.getElementById('tbText').value;

            myCustomObject.ChangeText(newText);
        }

        function buttonClick2() {
            var newText = document.getElementById('tbText2').value;

            myCustomObject2.ChangeText(newText);
        }
    </script>
</head>
<body>
    <input type="text" id="tbText" />
    <input type="button" value="Change" onclick="buttonClick();" />

    <input type="text" id="tbText2" />
    <input type="button" value="Change" onclick="buttonClick2();" />
</body>

Dominik Kirschenhofer
  • 1,205
  • 1
  • 13
  • 27
0

Usage: jsfiddle

This is a naive approach but might work for some applications:

CustomEventTarget.prototype = {

    'constructor': CustomEventTarget,

    on:   function( ev, el ) { this.eventTarget.addEventListener( ev, el ) },
    off:  function( ev, el ) { this.eventTarget.removeEventListener( ev, el ) },
    emit: function( ev ) { this.eventTarget.dispatchEvent( ev ) }

}

function CustomEventTarget() { this.eventTarget = new EventTarget }
flcoder
  • 713
  • 4
  • 14