最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Custom Events in CLASS - Stack Overflow

programmeradmin2浏览0评论

I need to launch custom events from CLASS. I know to do this with DOM objects and jquery, using triggerHandler, like $(object)..triggerHandler("inputChange", {param:X}); The problem is when i try this with a Class, like this:

    var MyClass = (function(){

        var static_var = 1;

        var MyClass = function () {

            var privateVar;
            var privateFn = function(){ alert('Im private!'); };

            this.someProperty = 5;
            this.someFunction = function () {
                alert('Im public!');
            };
            this.say = function() {
                alert('Num ' + this.someProperty);
                $(this).triggerHandler("eventCustom");
            }
            this.alter = function() {
                this.someProperty ++;
            }
        };

        return MyClass;

    })();

    TheClass = new MyClass();

    $(TheClass).on('eventCustom', function() {
        alert('Event!');
    });

    TheClass.say();

This doesn't launch warnings or errors, but the events listener is not working (or event is not dispatched). I think the jQuery event system doesn't work with not DOM object, correct?

Any other way (I need events, not callbacks for my specific case) to launch the events?

Thanks a lot!

I need to launch custom events from CLASS. I know to do this with DOM objects and jquery, using triggerHandler, like $(object)..triggerHandler("inputChange", {param:X}); The problem is when i try this with a Class, like this:

    var MyClass = (function(){

        var static_var = 1;

        var MyClass = function () {

            var privateVar;
            var privateFn = function(){ alert('Im private!'); };

            this.someProperty = 5;
            this.someFunction = function () {
                alert('Im public!');
            };
            this.say = function() {
                alert('Num ' + this.someProperty);
                $(this).triggerHandler("eventCustom");
            }
            this.alter = function() {
                this.someProperty ++;
            }
        };

        return MyClass;

    })();

    TheClass = new MyClass();

    $(TheClass).on('eventCustom', function() {
        alert('Event!');
    });

    TheClass.say();

This doesn't launch warnings or errors, but the events listener is not working (or event is not dispatched). I think the jQuery event system doesn't work with not DOM object, correct?

Any other way (I need events, not callbacks for my specific case) to launch the events?

Thanks a lot!

Share Improve this question edited Feb 13, 2017 at 16:55 marc_s 754k184 gold badges1.4k silver badges1.5k bronze badges asked Jun 18, 2013 at 9:20 ZenthZenth 8112 gold badges9 silver badges23 bronze badges 1
  • "i think the jqeury event system dosent work with not DOM object" Incorrect: api.jquery.com/jQuery/#working-with-plain-objects. The question is whether it works with objects created with constructor functions. – Felix Kling Commented Jun 18, 2013 at 9:22
Add a comment  | 

2 Answers 2

Reset to default 13

I wrote an ES6 event class for nowadays in under 100 lines of code without using JQuery. If you don't want to use DOM-events you can extend your class, which should deal with Events.

For listening to events, you can use on, once, onReady, onceReady. On is execute the callbackfunction every time the label is trigger. Once only one time. The "ready"-functions execute the callback, if the label had been already triggerd before.

For triggering an event, use a trigger. To remove an eventhandler, use off.

I hope the example makes it clear:

class ClassEventsES6 {
                constructor() {
                    this.listeners = new Map();
                    this.onceListeners = new Map();
                    this.triggerdLabels = new Map();
                }

                // help-function for onReady and onceReady
                // the callbackfunction will execute, 
                // if the label has already been triggerd with the last called parameters
                _fCheckPast(label, callback) {
                    if (this.triggerdLabels.has(label)) {
                        callback(this.triggerdLabels.get(label));
                        return true;
                    } else {
                        return false;
                    }
                }

                // execute the callback everytime the label is trigger
                on(label, callback, checkPast = false) {
                    this.listeners.has(label) || this.listeners.set(label, []);
                    this.listeners.get(label).push(callback);
                    if (checkPast)
                        this._fCheckPast(label, callback);
                }

                // execute the callback everytime the label is trigger
                // check if the label had been already called 
                // and if so excute the callback immediately
                onReady(label, callback) {
                    this.on(label, callback, true);
                }

                // execute the callback onetime the label is trigger
                once(label, callback, checkPast = false) {
                    this.onceListeners.has(label) || this.onceListeners.set(label, []);
                    if (!(checkPast && this._fCheckPast(label, callback))) {
                        // label wurde nocht nicht aufgerufen und 
                        // der callback in _fCheckPast nicht ausgeführt
                        this.onceListeners.get(label).push(callback);
                }
                }
                // execute the callback onetime the label is trigger
                // or execute the callback if the label had been called already
                onceReady(label, callback) {
                    this.once(label, callback, true);
                }

                // remove the callback for a label
                off(label, callback = true) {
                    if (callback === true) {
                        // remove listeners for all callbackfunctions
                        this.listeners.delete(label);
                        this.onceListeners.delete(label);
                    } else {
                        // remove listeners only with match callbackfunctions
                        let _off = (inListener) => {
                            let listeners = inListener.get(label);
                            if (listeners) {
                                inListener.set(label, listeners.filter((value) => !(value === callback)));
                            }
                        };
                        _off(this.listeners);
                        _off(this.onceListeners);
                }
                }

                // trigger the event with the label 
                trigger(label, ...args) {
                    let res = false;
                    this.triggerdLabels.set(label, ...args); // save all triggerd labels for onready and onceready
                    let _trigger = (inListener, label, ...args) => {
                        let listeners = inListener.get(label);
                        if (listeners && listeners.length) {
                            listeners.forEach((listener) => {
                                listener(...args);
                            });
                            res = true;
                        }
                    };
                    _trigger(this.onceListeners, label, ...args);
                    _trigger(this.listeners, label, ...args);
                    this.onceListeners.delete(label); // callback for once executed, so delete it.
                    return res;
                }
            }
            
// +++ here starts the example +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
class TestClassEvents extends ClassEventsES6 {
     constructor() {
        super();
        this.once('sayHallo', this.fStartToTalk);
        this.on('sayHallo', this.fSayHallo);
     }

     fStartToTalk() {
         console.log('I start to talk... ');
     }

     fSayHallo(name = 'Nobody') {
        console.log('Hallo ' + name);
     }
}

let testClassEvents = new TestClassEvents();

testClassEvents.trigger('sayHallo', 'Tony');
testClassEvents.trigger('sayHallo', 'Tim');

testClassEvents.onReady('sayHallo', e => console.log('I already said hello to ' + e));
testClassEvents.trigger('sayHallo', 'Angie');
testClassEvents.off('sayHallo');
testClassEvents.trigger('sayHallo', 'Peter');
console.log('I dont say hallo to Peter, because the event is off!')

Your understanding of how javascript works is limited since you are approaching it from a traditional OOP point of view. Take a look at this fiddle http://jsfiddle.net/9pCmh/ & you will see that you can actually pass functions as variables to other functions. There are no classes in javascript, only functions which can be closures which can be made to emulate traditional classes:

var MyClass = (function(){

    var static_var = 1;

    var MyClass = function ( callback ) {

        var privateVar;
        var privateFn = function(){ alert('Im private!'); };

        this.someProperty = 5;
        this.someFunction = function () {
            alert('Im public!');
        };
        this.say = function() {
            alert('Num ' + this.someProperty);
            callback();
        }
        this.alter = function() {
            this.someProperty ++;
        }
    };

    return MyClass;

})();

TheClass = new MyClass(function() {
    alert('Event!');
});

TheClass.say();

Alternatively you could create a function in your "class" to configure the callback/trigger instead of passing it into the constructor.

Have a look at this as a start for your further reading on this concept... How do JavaScript closures work?

Edit

To appease those critics looking for an eventQueue here is an updated jsfiddle :)

http://jsfiddle.net/Qxtnd/9/

var events = new function() {
  var _triggers = {};

  this.on = function(event,callback) {
      if(!_triggers[event])
          _triggers[event] = [];
      _triggers[event].push( callback );
    }

  this.triggerHandler = function(event,params) {
      if( _triggers[event] ) {
          for( i in _triggers[event] )
              _triggers[event][i](params);
      }
  }
};

var MyClass = (function(){

      var MyClass = function () {

          this.say = function() {
              alert('Num ' + this.someProperty);
              events.triggerHandler('eventCustom');
          }
      };

      return MyClass;

  })();

  TheClass = new MyClass();

  events.on('eventCustom', function() {
      alert('Event!');
  });
  events.on('eventCustom', function() {
      alert('Another Event!');
  });

  TheClass.say();
发布评论

评论列表(0)

  1. 暂无评论