diff --git a/src/Scope.js b/src/Scope.js index e978b65980b5..12ac2833e59f 100644 --- a/src/Scope.js +++ b/src/Scope.js @@ -99,6 +99,7 @@ function Scope() { this.$destructor = noop; this['this'] = this.$root = this; this.$$asyncQueue = []; + this.$$listeners = {}; } /** @@ -155,8 +156,8 @@ Scope.prototype = { * the scope and its child scopes to be permanently detached from the parent and thus stop * participating in model change detection and listener notification by invoking. * - * @param {function()=} constructor Constructor function which the scope should behave as. - * @param {curryArguments=} ... Any additional arguments which are curried into the constructor. + * @param {function()=} Class Constructor function which the scope should be applied to the scope. + * @param {...*} curryArguments Any additional arguments which are curried into the constructor. * See {@link guide/dev_guide.di dependency injection}. * @returns {Object} The newly created child scope. * @@ -169,6 +170,7 @@ Scope.prototype = { Child.prototype = this; child = new Child(); child['this'] = child; + child.$$listeners = {}; child.$parent = this; child.$id = nextUid(); child.$$asyncQueue = []; @@ -392,12 +394,15 @@ Scope.prototype = { * scope and its children. Removal also implies that the current scope is eligible for garbage * collection. * + * The destructing scope emits an `$destroy` {@link angular.scope.$emit event}. + * * The `$destroy()` is usually used by directives such as * {@link angular.widget.@ng:repeat ng:repeat} for managing the unrolling of the loop. * */ $destroy: function() { if (this.$root == this) return; // we can't remove the root node; + this.$emit('$destroy'); var parent = this.$parent; if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling; @@ -413,7 +418,7 @@ Scope.prototype = { * @function * * @description - * Executes the expression on the current scope returning the result. Any exceptions in the + * Executes the `expression` on the current scope returning the result. Any exceptions in the * expression are propagated (uncaught). This is useful when evaluating engular expressions. * * # Example @@ -520,9 +525,173 @@ Scope.prototype = { } finally { this.$root.$digest(); } + }, + + /** + * @workInProgress + * @ngdoc function + * @name angular.scope.$on + * @function + * + * @description + * Listen on events of a given type. See {@link angular.scope.$emit $emit} for discussion of + * event life cycle. + * + * @param {string} name Event name to listen on. + * @param {function(event)} listener Function to call when the event is emitted. + * + * The event listener function format is: `function(event)`. The `event` object passed into the + * listener has the following attributes + * - `targetScope` - {Scope}: the scope on which the event was `$emit`-ed or `$broadcast`-ed. + * - `currentScope` - {Scope}: the current scope which is handling the event. + * - `name` - {string}: Name of the event. + * - `cancel` - {function=}: calling `cancel` function will cancel further event propagation + * (available only for events that were `$emit`-ed). + */ + $on: function(name, listener) { + var namedListeners = this.$$listeners[name]; + if (!namedListeners) { + this.$$listeners[name] = namedListeners = []; + } + namedListeners.push(listener); + }, + + /** + * @workInProgress + * @ngdoc function + * @name angular.scope.$removeListener + * @function + * + * @description + * Remove the on listener registered by {@link angular.scope.$on $on}. + * + * @param {string} name Event name to remove on. + * @param {function} listener Function to remove. + */ + $removeListener: function(name, listener) { + var namedListeners = this.$$listeners[name]; + var i; + if (namedListeners) { + i = namedListeners.indexOf(listener); + namedListeners.splice(i, 1); + } + }, + + /** + * @workInProgress + * @ngdoc function + * @name angular.scope.$emit + * @function + * + * @description + * Dispatches an event `name` upwards through the scope hierarchy notifying the + * registered {@link angular.scope.$on} listeners. + * + * The event life cycle starts at the scope on which `$emit` was called. All + * {@link angular.scope.$on listeners} listening for `name` event on this scope get notified. + * Afterwards, the event traverses upwards toward the root scope and calls all registered + * listeners along the way. The event will stop propagating if one of the listeners cancels it. + * + * Any exception emmited from the {@link angular.scope.$on listeners} will be passed + * onto the {@link angular.service.$exceptionHandler $exceptionHandler} service. + * + * @param {string} name Event name to emit. + * @param {...*} args Optional set of arguments which will be passed onto the event listeners. + */ + $emit: function(name, args) { + var empty = [], + namedListeners, + canceled = false, + scope = this, + event = { + name: name, + targetScope: scope, + cancel: function(){canceled = true;} + }, + listenerArgs = concat([event], arguments, 1), + i, length; + + do { + namedListeners = scope.$$listeners[name] || empty; + event.currentScope = scope; + for (i=0, length=namedListeners.length; i'; + } + + beforeEach(function() { + log = ''; + child = root.$new(); + grandChild = child.$new(); + greatGrandChild = grandChild.$new(); + + root.id = 0; + child.id = 1; + grandChild.id = 2; + greatGrandChild.id = 3; + + root.$on('myEvent', logger); + child.$on('myEvent', logger); + grandChild.$on('myEvent', logger); + greatGrandChild.$on('myEvent', logger); + }); + + + it('should bubble event up to the root scope', function() { + grandChild.$emit('myEvent'); + expect(log).toEqual('2>1>0>'); + }); + + + it('should dispatch exceptions to the $exceptionHandler', function() { + child.$on('myEvent', function() { throw 'bubbleException'; }); + grandChild.$emit('myEvent'); + expect(log).toEqual('2>1>0>'); + expect(mockHandler.errors).toEqual(['bubbleException']); + }); + + + it('should allow cancelation of event propagation', function() { + child.$on('myEvent', function(event){ event.cancel(); }); + grandChild.$emit('myEvent'); + expect(log).toEqual('2>1>'); + }); + + + it('should remove event listener', function() { + function eventFn(){ + log += 'abc;'; + } + + child.$on('abc', eventFn); + child.$emit('abc'); + expect(log).toEqual('abc;'); + log = ''; + child.$removeListener('abc', eventFn); + child.$emit('abc'); + expect(log).toEqual(''); + }); + + + it('should forward method arguments', function() { + child.$on('abc', function(event, arg1, arg2){ + expect(event.name).toBe('abc'); + expect(arg1).toBe('arg1'); + expect(arg2).toBe('arg2'); + }); + child.$emit('abc', 'arg1', 'arg2'); + }); + + describe('event object', function() { + it('should have methods/properties', function() { + var event; + child.$on('myEvent', function(e){ + expect(e.targetScope).toBe(grandChild); + expect(e.currentScope).toBe(child); + expect(e.name).toBe('myEvent'); + event = e; + }); + grandChild.$emit('myEvent'); + expect(event).toBeDefined(); + }); + }); + }); + + + describe('$broadcast', function() { + describe('event propagation', function() { + var log, child1, child2, child3, grandChild11, grandChild21, grandChild22, + greatGrandChild211; + + function logger(event) { + log += event.currentScope.id + '>'; + } + + beforeEach(function() { + log = ''; + child1 = root.$new(); + child2 = root.$new(); + child3 = root.$new(); + grandChild11 = child1.$new(); + grandChild21 = child2.$new(); + grandChild22 = child2.$new(); + greatGrandChild211 = grandChild21.$new(); + + root.id = 0; + child1.id = 1; + child2.id = 2; + child3.id = 3; + grandChild11.id = 11; + grandChild21.id = 21; + grandChild22.id = 22; + greatGrandChild211.id = 211; + + root.$on('myEvent', logger); + child1.$on('myEvent', logger); + child2.$on('myEvent', logger); + child3.$on('myEvent', logger); + grandChild11.$on('myEvent', logger); + grandChild21.$on('myEvent', logger); + grandChild22.$on('myEvent', logger); + greatGrandChild211.$on('myEvent', logger); + + // R + // / | \ + // 1 2 3 + // / / \ + // 11 21 22 + // | + // 211 + }); + + + it('should broadcast an event from the root scope', function() { + root.$broadcast('myEvent'); + expect(log).toBe('0>1>11>2>21>211>22>3>'); + }); + + + it('should broadcast an event from a child scope', function() { + child2.$broadcast('myEvent'); + expect(log).toBe('2>21>211>22>'); + }); + + + it('should broadcast an event from a leaf scope', function() { + grandChild22.$broadcast('myEvent'); + expect(log).toBe('22>'); + }); + + + it('should not not fire any listeners for other events', function() { + root.$broadcast('fooEvent'); + expect(log).toBe(''); + }); + }); + + + describe('listener', function() { + it('should receive event object', function() { + var scope = angular.scope(), + child = scope.$new(), + event; + + child.$on('fooEvent', function(e) { + event = e; + }); + scope.$broadcast('fooEvent'); + + expect(event.name).toBe('fooEvent'); + expect(event.targetScope).toBe(scope); + expect(event.currentScope).toBe(child); + }); + + + it('should support passing messages as varargs', function() { + var scope = angular.scope(), + child = scope.$new(), + args; + + child.$on('fooEvent', function() { + args = arguments; + }); + scope.$broadcast('fooEvent', 'do', 're', 'me', 'fa'); + + expect(args.length).toBe(5); + expect([].splice.call(args, 1)).toEqual(['do', 're', 'me', 'fa']); + }); + }); + }); + }); });