feat(Directives): add the ability to declaratively bind events

relates to #621
This commit is contained in:
Victor Berchet
2015-03-06 15:44:59 +01:00
parent 86e9dd68a4
commit bfa18ffd9b
9 changed files with 259 additions and 49 deletions

View File

@ -8,16 +8,19 @@ export class Directive {
lightDomServices:any; //List;
implementsTypes:any; //List;
lifecycle:any; //List
events:any; //List
@CONST()
constructor({
selector,
bind,
events,
lightDomServices,
implementsTypes,
lifecycle
}:{
selector:string,
bind:any,
events: any,
lightDomServices:List,
implementsTypes:List,
lifecycle:List
@ -27,6 +30,7 @@ export class Directive {
this.lightDomServices = lightDomServices;
this.implementsTypes = implementsTypes;
this.bind = bind;
this.events = events;
this.lifecycle = lifecycle;
}
@ -37,15 +41,14 @@ export class Directive {
export class Component extends Directive {
//TODO: vsavkin: uncomment it once the issue with defining fields in a sublass works
lightDomServices:any; //List;
shadowDomServices:any; //List;
componentServices:any; //List;
lifecycle:any; //List
@CONST()
constructor({
selector,
bind,
events,
lightDomServices,
shadowDomServices,
componentServices,
@ -54,6 +57,7 @@ export class Component extends Directive {
}:{
selector:String,
bind:Object,
events:Object,
lightDomServices:List,
shadowDomServices:List,
componentServices:List,
@ -64,15 +68,14 @@ export class Component extends Directive {
super({
selector: selector,
bind: bind,
events: events,
lightDomServices: lightDomServices,
implementsTypes: implementsTypes,
lifecycle: lifecycle
});
this.lightDomServices = lightDomServices;
this.shadowDomServices = shadowDomServices;
this.componentServices = componentServices;
this.lifecycle = lifecycle;
}
}
@ -82,6 +85,7 @@ export class Decorator extends Directive {
constructor({
selector,
bind,
events,
lightDomServices,
implementsTypes,
lifecycle,
@ -89,6 +93,7 @@ export class Decorator extends Directive {
}:{
selector:string,
bind:any,
events:any,
lightDomServices:List,
implementsTypes:List,
lifecycle:List,
@ -99,6 +104,7 @@ export class Decorator extends Directive {
super({
selector: selector,
bind: bind,
events: events,
lightDomServices: lightDomServices,
implementsTypes: implementsTypes,
lifecycle: lifecycle
@ -111,6 +117,7 @@ export class Viewport extends Directive {
constructor({
selector,
bind,
events,
lightDomServices,
implementsTypes,
lifecycle
@ -125,6 +132,7 @@ export class Viewport extends Directive {
super({
selector: selector,
bind: bind,
events: events,
lightDomServices: lightDomServices,
implementsTypes: implementsTypes,
lifecycle: lifecycle

View File

@ -1,6 +1,6 @@
import {ProtoElementInjector} from './element_injector';
import {DirectiveMetadata} from './directive_metadata';
import {List, Map} from 'angular2/src/facade/collection';
import {List, StringMap} from 'angular2/src/facade/collection';
import {ProtoView} from './view';
export class ElementBinder {
@ -10,7 +10,7 @@ export class ElementBinder {
textNodeIndices:List<int>;
hasElementPropertyBindings:boolean;
nestedProtoView: ProtoView;
events:Map;
events:StringMap;
constructor(
protoElementInjector: ProtoElementInjector, componentDirective:DirectiveMetadata,
viewportDirective:DirectiveMetadata) {

View File

@ -1,6 +1,6 @@
import {FIELD, isPresent, isBlank, Type, int, BaseException} from 'angular2/src/facade/lang';
import {Math} from 'angular2/src/facade/math';
import {List, ListWrapper, MapWrapper} from 'angular2/src/facade/collection';
import {List, ListWrapper, MapWrapper, StringMap, StringMapWrapper} from 'angular2/src/facade/collection';
import {Injector, Key, Dependency, bind, Binding, NoProviderError, ProviderError, CyclicDependencyError} from 'angular2/di';
import {Parent, Ancestor} from 'angular2/src/core/annotations/visibility';
import {EventEmitter, PropertySetter} from 'angular2/src/core/annotations/di';
@ -18,6 +18,8 @@ var MAX_DEPTH = Math.pow(2, 30) - 1;
var _undefined = new Object();
var _noop = function(_) {};
var _staticKeys;
class StaticKeys {
@ -270,9 +272,9 @@ export class ProtoElementInjector {
}
}
instantiate(parent:ElementInjector, host:ElementInjector, eventCallbacks,
reflector: Reflector):ElementInjector {
return new ElementInjector(this, parent, host, eventCallbacks, reflector);
instantiate(parent:ElementInjector, host:ElementInjector, events,
reflector: Reflector):ElementInjector {
return new ElementInjector(this, parent, host, events, reflector);
}
directParent(): ProtoElementInjector {
@ -325,11 +327,11 @@ export class ElementInjector extends TreeNode {
_obj9:any;
_preBuiltObjects;
_constructionCounter;
_eventCallbacks;
_events:StringMap;
_refelector: Reflector;
constructor(proto:ProtoElementInjector, parent:ElementInjector, host:ElementInjector,
eventCallbacks: Map, reflector: Reflector) {
events: StringMap, reflector: Reflector) {
super(parent);
if (isPresent(parent) && isPresent(host)) {
throw new BaseException('Only either parent or host is allowed');
@ -348,7 +350,7 @@ export class ElementInjector extends TreeNode {
this._preBuiltObjects = null;
this._lightDomAppInjector = null;
this._shadowDomAppInjector = null;
this._eventCallbacks = eventCallbacks;
this._events = events;
this._obj0 = null;
this._obj1 = null;
this._obj2 = null;
@ -513,13 +515,13 @@ export class ElementInjector extends TreeNode {
_buildEventEmitter(dep) {
var view = this._getPreBuiltObjectByKeyId(StaticKeys.instance().viewId);
if (isPresent(this._eventCallbacks)) {
var callback = MapWrapper.get(this._eventCallbacks, dep.eventEmitterName);
if (isPresent(callback)) {
return ProtoView.buildInnerCallback(callback, view);
if (isPresent(this._events)) {
var eventMap = StringMapWrapper.get(this._events, dep.eventEmitterName);
if (isPresent(eventMap)) {
return ProtoView.buildEventCallback(eventMap, view, this._proto.index);
}
}
return (_) => {};
return _noop;
}
_buildPropSetter(dep) {

View File

@ -183,7 +183,7 @@ function getElementDescription(domElement):string {
buf.add("<");
buf.add(DOM.tagName(domElement).toLowerCase());
// show id and class first to ease element identification
addDescriptionAttribute(buf, "id", MapWrapper.get(atts, "id"));
addDescriptionAttribute(buf, "class", MapWrapper.get(atts, "class"));

View File

@ -152,7 +152,9 @@ export class ElementBinderBuilder extends CompileStep {
if (isPresent(current.eventBindings)) {
this._bindEvents(protoView, current);
}
this._bindDirectiveProperties(current.getAllDirectives(), current);
var directives = current.getAllDirectives();
this._bindDirectiveProperties(directives, current);
this._bindDirectiveEvents(directives, current);
} else if (isPresent(parent)) {
elementBinder = parent.inheritedElementBinder;
}
@ -199,6 +201,19 @@ export class ElementBinderBuilder extends CompileStep {
});
}
_bindDirectiveEvents(directives: List<DirectiveMetadata>, compileElement: CompileElement) {
for (var directiveIndex = 0; directiveIndex < directives.length; directiveIndex++) {
var directive = directives[directiveIndex];
var annotation = directive.annotation;
if (isBlank(annotation.events)) continue;
var protoView = compileElement.inheritedProtoView;
StringMapWrapper.forEach(annotation.events, (action, eventName) => {
var expression = this._parser.parseAction(action, compileElement.elementDescription);
protoView.bindEvent(eventName, expression, directiveIndex);
});
}
}
_bindDirectiveProperties(directives: List<DirectiveMetadata>,
compileElement: CompileElement) {
var protoView = compileElement.inheritedProtoView;

View File

@ -1,6 +1,6 @@
import {DOM} from 'angular2/src/dom/dom_adapter';
import {Promise} from 'angular2/src/facade/async';
import {ListWrapper, MapWrapper, StringMapWrapper, List} from 'angular2/src/facade/collection';
import {ListWrapper, MapWrapper, Map, StringMapWrapper, List} from 'angular2/src/facade/collection';
import {AST, ContextWithVariableBindings, ChangeDispatcher, ProtoChangeDetector, ChangeDetector, ChangeRecord}
from 'angular2/change_detection';
@ -326,8 +326,8 @@ export class ProtoView {
}
var elementsWithBindings = ListWrapper.createFixedSize(elementsWithBindingsDynamic.length);
for (var i = 0; i < elementsWithBindingsDynamic.length; ++i) {
elementsWithBindings[i] = elementsWithBindingsDynamic[i];
for (var binderIdx = 0; binderIdx < elementsWithBindingsDynamic.length; ++binderIdx) {
elementsWithBindings[binderIdx] = elementsWithBindingsDynamic[binderIdx];
}
var viewNodes;
@ -353,13 +353,13 @@ export class ProtoView {
var viewContainers = [];
var componentChildViews = [];
for (var i = 0; i < binders.length; i++) {
var binder = binders[i];
for (var binderIdx = 0; binderIdx < binders.length; binderIdx++) {
var binder = binders[binderIdx];
var element;
if (i === 0 && this.rootBindingOffset === 1) {
if (binderIdx === 0 && this.rootBindingOffset === 1) {
element = rootElementClone;
} else {
element = elementsWithBindings[i - this.rootBindingOffset];
element = elementsWithBindings[binderIdx - this.rootBindingOffset];
}
var elementInjector = null;
@ -376,7 +376,7 @@ export class ProtoView {
ListWrapper.push(rootElementInjectors, elementInjector);
}
}
elementInjectors[i] = elementInjector;
elementInjectors[binderIdx] = elementInjector;
if (binder.hasElementPropertyBindings) {
ListWrapper.push(elementsWithPropertyBindings, element);
@ -421,15 +421,15 @@ export class ProtoView {
// preBuiltObjects
if (isPresent(elementInjector)) {
preBuiltObjects[i] = new PreBuiltObjects(view, new NgElement(element), viewContainer,
preBuiltObjects[binderIdx] = new PreBuiltObjects(view, new NgElement(element), viewContainer,
lightDom, bindingPropagationConfig);
}
// events
if (isPresent(binder.events)) {
MapWrapper.forEach(binder.events, (expr, eventName) => {
StringMapWrapper.forEach(binder.events, (eventMap, eventName) => {
if (isBlank(elementInjector) || !elementInjector.hasEventEmitter(eventName)) {
var handler = ProtoView.buildInnerCallback(expr, view);
var handler = ProtoView.buildEventCallback(eventMap, view, binderIdx);
eventManager.addEventListener(element, eventName, handler);
}
});
@ -446,17 +446,39 @@ export class ProtoView {
this._viewPool.push(view);
}
static buildInnerCallback(expr:AST, view:View) {
/**
* Create an event callback invoked in the context of the enclosing View
*
* @param {AST} expr
* @param {View} view
* @returns {Function}
*/
/**
* Creates the event callback.
*
* @param {Map} eventMap Map directiveIndexes to expressions
* @param {View} view
* @param {int} injectorIdx
* @returns {Function}
*/
static buildEventCallback(eventMap: Map, view:View, injectorIdx: int) {
var locals = MapWrapper.create();
return (event) => {
// Most of the time the event will be fired only when the view is
// in the live document. However, in a rare circumstance the
// view might get dehydrated, in between the event queuing up and
// firing.
// Most of the time the event will be fired only when the view is in the live document.
// However, in a rare circumstance the view might get dehydrated, in between the event
// queuing up and firing.
if (view.hydrated()) {
MapWrapper.set(locals, '$event', event);
var context = new ContextWithVariableBindings(view.context, locals);
expr.eval(context);
MapWrapper.forEach(eventMap, (expr, directiveIndex) => {
var context;
if (directiveIndex === -1) {
context = view.context;
} else {
context = view.elementInjectors[injectorIdx].getDirectiveAtIndex(directiveIndex);
}
expr.eval(new ContextWithVariableBindings(context, locals));
});
}
}
}
@ -505,14 +527,31 @@ export class ProtoView {
}
/**
* Adds an event binding for the last created ElementBinder via bindElement
* Adds an event binding for the last created ElementBinder via bindElement.
*
* If the directive index is a positive integer, the event is evaluated in the context of
* the given directive.
*
* If the directive index is -1, the event is evaluated in the context of the enclosing view.
*
* @param {string} eventName
* @param {AST} expression
* @param {int} directiveIndex The directive index in the binder or -1 when the event is not bound
* to a directive
*/
bindEvent(eventName:string, expression:AST) {
var elBinder = this.elementBinders[this.elementBinders.length-1];
if (isBlank(elBinder.events)) {
elBinder.events = MapWrapper.create();
bindEvent(eventName:string, expression:AST, directiveIndex: int = -1) {
var elBinder = this.elementBinders[this.elementBinders.length - 1];
var events = elBinder.events;
if (isBlank(events)) {
events = StringMapWrapper.create();
elBinder.events = events;
}
MapWrapper.set(elBinder.events, eventName, expression);
var event = StringMapWrapper.get(events, eventName);
if (isBlank(event)) {
event = MapWrapper.create();
StringMapWrapper.set(events, eventName, event);
}
MapWrapper.set(event, directiveIndex, expression);
}
/**