Browse Source

added scope option to observer

Adam Bowman 7 years ago
parent
commit
3c8a923d60
1 changed files with 9 additions and 4 deletions
  1. 9 4
      src/Tools/babylon.observable.ts

+ 9 - 4
src/Tools/babylon.observable.ts

@@ -33,7 +33,7 @@
      * Represent an Observer registered to a given Observable object.
      */
     export class Observer<T> {
-        constructor(public callback: (eventData: T, eventState: EventState) => void, public mask: number) {
+        constructor(public callback: (eventData: T, eventState: EventState) => void, public mask: number, public scope: any = null) {
         }
     }
 
@@ -62,13 +62,14 @@
          * @param callback the callback that will be executed for that Observer
          * @param mask the mask used to filter observers
          * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
+         * @param scope optional scope for the callback to be called from
          */
-        public add(callback: (eventData: T, eventState: EventState) => void, mask: number = -1, insertFirst = false): Observer<T> {
+        public add(callback: (eventData: T, eventState: EventState) => void, mask: number = -1, insertFirst = false, scope = null): Observer<T> {
             if (!callback) {
                 return null;
             }
 
-            var observer = new Observer(callback, mask);
+            var observer = new Observer(callback, mask, scope);
 
             if (insertFirst) {
                 this._observers.unshift(observer);
@@ -129,7 +130,11 @@
 
             for (var obs of this._observers) {
                 if (obs.mask & mask) {
-                    obs.callback(eventData, state);
+                    if(obs.scope){
+                        obs.callback.apply(obs.scope, [eventData, state])
+                    }else{
+                        obs.callback(eventData, state);
+                    }
                 }
                 if (state.skipNextObservers) {
                     return false;