From 93f7d67767b27df93fcbefb02b391f5587bbe0e2 Mon Sep 17 00:00:00 2001
From: Jone <350791117@qq.com>
Date: Mon, 28 Jan 2019 17:14:23 +0800
Subject: [PATCH] add node event
---
cocos/3d/ui/components/button-component.ts | 24 +-
.../components/editbox/edit-box-component.ts | 6 +-
.../3d/ui/components/editbox/edit-box-impl.ts | 2 +-
.../3d/ui/components/scroll-view-component.ts | 4 +-
cocos/3d/ui/components/slider-component.ts | 10 +-
.../ui/components/ui-transfrom-component.ts | 32 +-
cocos/core/event/event.ts | 55 +-
.../platform/event-manager/CCInputManager.ts | 35 +-
cocos/renderer/ui/ui.ts | 27 +-
cocos/scene-graph/node-event-enum.ts | 20 +
cocos/scene-graph/node-event-processor.ts | 601 ++++++++++++++++++
cocos/scene-graph/node.ts | 534 +---------------
12 files changed, 748 insertions(+), 602 deletions(-)
create mode 100644 cocos/scene-graph/node-event-enum.ts
create mode 100644 cocos/scene-graph/node-event-processor.ts
diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/3d/ui/components/button-component.ts
index 95bd18b3e7..61592ed92e 100644
--- a/cocos/3d/ui/components/button-component.ts
+++ b/cocos/3d/ui/components/button-component.ts
@@ -35,6 +35,7 @@ import { Color, Enum, Vec3 } from '../../../core/value-types/index';
import * as math from '../../../core/vmath/index';
import { Node } from '../../../scene-graph';
import { SpriteComponent } from './sprite-component';
+import { UIRenderComponent } from './ui-render-component';
/**
* !#en Enum for transition type.
@@ -510,7 +511,7 @@ export class ButtonComponent extends Component {
this._hovered = false;
// // Restore button status
const target = this.target;
- const renderComp = this.target.getComponent(cc.RenderComponent);
+ const renderComp = this.target.getComponent(UIRenderComponent);
const transition = this.transition;
if (transition === Transition.COLOR && this.interactable) {
renderComp.color = this.normalColor;
@@ -583,7 +584,7 @@ export class ButtonComponent extends Component {
this._transitionFinished = true;
}
- const renderComp = target.getComponent(cc.RenderComponent);
+ const renderComp = target.getComponent(UIRenderComponent);
if (this._transition === Transition.COLOR) {
renderComp.color = this._fromColor.lerp(this._toColor, ratio);
} else if (this.transition === Transition.SCALE) {
@@ -624,7 +625,9 @@ export class ButtonComponent extends Component {
this._pressed = true;
this._updateState();
- event && event.stopPropagation();
+ if(event){
+ event.propagationStopped = true
+ };
}
public _onTouchMove (event: Event | null) {
@@ -662,7 +665,10 @@ export class ButtonComponent extends Component {
}
this._applyTransition(state);
}
- event.stopPropagation();
+
+ if (event) {
+ event.propagationStopped = true
+ }
}
public _onTouchEnded (event: Event | null) {
@@ -674,7 +680,10 @@ export class ButtonComponent extends Component {
}
this._pressed = false;
this._updateState();
- event && event.stopPropagation();
+
+ if (event) {
+ event.propagationStopped = true
+ };
}
public _onTouchCancel () {
@@ -725,8 +734,11 @@ export class ButtonComponent extends Component {
public _updateColorTransition (state: string) {
const color = this[state + 'Color'];
const target = this._target;
+ if(!target){
+ return;
+ }
- const renderComp = target.getComponent(cc.RenderComponent);
+ const renderComp = target.getComponent(UIRenderComponent);
if (!renderComp) {
return;
}
diff --git a/cocos/3d/ui/components/editbox/edit-box-component.ts b/cocos/3d/ui/components/editbox/edit-box-component.ts
index fc6f9a32f8..40cbb00f91 100644
--- a/cocos/3d/ui/components/editbox/edit-box-component.ts
+++ b/cocos/3d/ui/components/editbox/edit-box-component.ts
@@ -720,21 +720,21 @@ export class EditBoxComponent extends Component {
if (this._impl) {
this._impl._onTouchBegan(event.touch);
}
- event.stopPropagation();
+ event.propagationStopped = true;
}
public _onTouchCancel (event) {
// if (this._impl) {
// this._impl._onTouchCancel();
// }
- event.stopPropagation();
+ event.propagationStopped = true;
}
public _onTouchEnded (event) {
if (this._impl) {
this._impl._onTouchEnded();
}
- event.stopPropagation();
+ event.propagationStopped = true;
}
/**
diff --git a/cocos/3d/ui/components/editbox/edit-box-impl.ts b/cocos/3d/ui/components/editbox/edit-box-impl.ts
index 47aa5c7fdb..59b06fb3a4 100644
--- a/cocos/3d/ui/components/editbox/edit-box-impl.ts
+++ b/cocos/3d/ui/components/editbox/edit-box-impl.ts
@@ -690,7 +690,7 @@ function registerInputEventListener (tmpEdTxt: HTMLElement, editBoxImpl: EditBox
cbs.keypress = function (e) {
if (e.keyCode === macro.KEY.enter) {
- e.stopPropagation();
+ e.propagationStopped = true;
if (editBoxImpl.delegate && editBoxImpl.delegate.editBoxEditingReturn) {
editBoxImpl.delegate.editBoxEditingReturn();
diff --git a/cocos/3d/ui/components/scroll-view-component.ts b/cocos/3d/ui/components/scroll-view-component.ts
index 8c96d96499..fdddf711e7 100644
--- a/cocos/3d/ui/components/scroll-view-component.ts
+++ b/cocos/3d/ui/components/scroll-view-component.ts
@@ -945,7 +945,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
//This is for Scrollview as children of a Button
_stopPropagationIfTargetIsMe(event) {
if (event.eventPhase === cc.Event.AT_TARGET && event.target === this.node) {
- event.stopPropagation();
+ event.propagationStopped = true;
}
}
@@ -1002,7 +1002,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
this._handleReleaseLogic(touch);
}
if (this._touchMoved) {
- event.stopPropagation();
+ event.propagationStopped = true;
} else {
this._stopPropagationIfTargetIsMe(event);
}
diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts
index 6e96eef091..535538dc04 100644
--- a/cocos/3d/ui/components/slider-component.ts
+++ b/cocos/3d/ui/components/slider-component.ts
@@ -201,7 +201,7 @@ export class SliderComponent extends Component {
this._touchHandle = true;
this._offset = this._handle && this._handle.node.uiTransfromComp && this._handle.node.uiTransfromComp.convertToNodeSpaceAR((event as EventTouch).touch.getLocation());
- event.stopPropagation();
+ event.propagationStopped = true;
}
public _onTouchBegan (event: Event) {
@@ -211,25 +211,25 @@ export class SliderComponent extends Component {
this._handleSliderLogic((event as EventTouch).touch);
}
- event.stopPropagation();
+ event.propagationStopped = true;
}
public _onTouchMoved (event: Event) {
if (!this._dragging) { return; }
this._handleSliderLogic((event as EventTouch).touch);
- event.stopPropagation();
+ event.propagationStopped = true;
}
public _onTouchEnded (event: Event) {
this._dragging = false;
this._touchHandle = false;
this._offset = cc.v2();
- event.stopPropagation();
+ event.propagationStopped = true;
}
public _onTouchCancelled (event: Event) {
this._dragging = false;
- event.stopPropagation();
+ event.propagationStopped = true;
}
public _handleSliderLogic (touch) {
diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts
index bc113e7d4f..749d5d8b9f 100644
--- a/cocos/3d/ui/components/ui-transfrom-component.ts
+++ b/cocos/3d/ui/components/ui-transfrom-component.ts
@@ -148,33 +148,33 @@ export class UITransformComponent extends Component {
*/
public setContentSize (size: Size|number, height?: number) {
const locContentSize = this._contentSize;
- // var clone;
+ let clone;
if (height === undefined) {
size = size as Size;
if ((size.width === locContentSize.width) && (size.height === locContentSize.height)) {
return;
}
- // if (CC_EDITOR) {
- // clone = cc.size(locContentSize.width, locContentSize.height);
- // }
+ if (CC_EDITOR) {
+ clone = cc.size(locContentSize.width, locContentSize.height);
+ }
locContentSize.width = size.width;
locContentSize.height = size.height;
} else {
if ((size === locContentSize.width) && (height === locContentSize.height)) {
return;
}
- // if (CC_EDITOR) {
- // clone = cc.size(locContentSize.width, locContentSize.height);
- // }
+ if (CC_EDITOR) {
+ clone = cc.size(locContentSize.width, locContentSize.height);
+ }
locContentSize.width = size;
locContentSize.height = height;
}
- // if (CC_EDITOR) {
- // this.emit(EventType.SIZE_CHANGED, clone);
- // }
- // else {
- this.node.emit(EventType.SIZE_CHANGED);
- // }
+ if (CC_EDITOR) {
+ this.node.emit(EventType.SIZE_CHANGED, clone);
+ }
+ else {
+ this.node.emit(EventType.SIZE_CHANGED);
+ }
}
/**
@@ -221,17 +221,17 @@ export class UITransformComponent extends Component {
// }
}
- public isHit (point: Vec2, listener: Event|null = null) {
+ public isHit(point: Vec2, listener: EventListener) {
const w = this._contentSize.width;
const h = this._contentSize.height;
const cameraPt = _vec2a;
const testPt = _vec2b;
- const renderComp = this.node.getComponent(cc.RenderComponent);
+ const renderComp = this.node.getComponent(cc.UIRenderComponent);
if (!renderComp) {
return false;
}
- const canvas = cc.CanvasComponent.findView(renderComp);
+ const canvas = cc.director.root.ui.getScreen(renderComp.visibility);
if (!canvas) {
return;
}
diff --git a/cocos/core/event/event.ts b/cocos/core/event/event.ts
index 01af21145a..aa8f02e0ed 100644
--- a/cocos/core/event/event.ts
+++ b/cocos/core/event/event.ts
@@ -129,15 +129,18 @@ export default class Event {
*/
public eventPhase = 0;
- /*
- * Indicates whether or not event.stopPropagation() has been called on the event.
- */
- private _propagationStopped = false;
+ /**
+ * !#en Stops propagation for current event.
+ * !#zh 停止传递当前事件。
+ */
+ public propagationStopped = false;
- /*
- * Indicates whether or not event.stopPropagationImmediate() has been called on the event.
- */
- private _propagationImmediateStopped = false;
+ /**
+ * !#en Stops propagation for current event immediately,
+ * the event won't even be dispatched to the listeners attached in the current target.
+ * !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。
+ */
+ public propagationImmediateStopped = false;
/**
* @param type - The name of the event (case-sensitive), e.g. "click", "fire", or "submit"
@@ -157,8 +160,8 @@ export default class Event {
this.target = null;
this.currentTarget = null;
this.eventPhase = Event.NONE;
- this._propagationStopped = false;
- this._propagationImmediateStopped = false;
+ this.propagationStopped = false;
+ this.propagationImmediateStopped = false;
}
/**
@@ -170,29 +173,29 @@ export default class Event {
this.bubbles = bubbles || false;
}
- /**
- * !#en Stops propagation for current event.
- * !#zh 停止传递当前事件。
- */
- public stopPropagation () {
- this._propagationStopped = true;
- }
+ // /**
+ // * !#en Stops propagation for current event.
+ // * !#zh 停止传递当前事件。
+ // */
+ // public stopPropagation () {
+ // this.propagationStopped = true;
+ // }
- /**
- * !#en Stops propagation for current event immediately,
- * the event won't even be dispatched to the listeners attached in the current target.
- * !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。
- */
- public stopPropagationImmediate () {
- this._propagationImmediateStopped = true;
- }
+ // /**
+ // * !#en Stops propagation for current event immediately,
+ // * the event won't even be dispatched to the listeners attached in the current target.
+ // * !#zh 立即停止当前事件的传递,事件甚至不会被分派到所连接的当前目标。
+ // */
+ // public stopPropagationImmediate () {
+ // this.propagationImmediateStopped = true;
+ // }
/**
* !#en Checks whether the event has been stopped.
* !#zh 检查该事件是否已经停止传递.
*/
public isStopped () {
- return this._propagationStopped || this._propagationImmediateStopped;
+ return this.propagationStopped || this.propagationImmediateStopped;
}
/**
diff --git a/cocos/core/platform/event-manager/CCInputManager.ts b/cocos/core/platform/event-manager/CCInputManager.ts
index 9820040367..570595c08e 100644
--- a/cocos/core/platform/event-manager/CCInputManager.ts
+++ b/cocos/core/platform/event-manager/CCInputManager.ts
@@ -117,20 +117,19 @@ class InputManager {
}
const index = locTouchIntDict[touchID];
if (index === undefined) {
- continue;
+ const unusedIndex = this._getUnUsedIndex();
+ if (unusedIndex === -1) {
+ cc.logID(2300, unusedIndex);
+ continue;
+ }
+ // curTouch = this._touches[unusedIndex] = touch;
+ const curTouch = new CCTouch(touch._point.x, touch._point.y, touch.getID());
+ this._touches[unusedIndex] = curTouch;
+ curTouch._lastModified = now;
+ curTouch._setPrevPoint(touch._prevPoint);
+ locTouchIntDict[touchID] = unusedIndex;
+ handleTouches.push(curTouch);
}
- const unusedIndex = this._getUnUsedIndex();
- if (unusedIndex === -1) {
- cc.logID(2300, unusedIndex);
- continue;
- }
- // curTouch = this._touches[unusedIndex] = touch;
- const curTouch = new CCTouch(touch._point.x, touch._point.y, touch.getID());
- this._touches[unusedIndex] = curTouch;
- curTouch._lastModified = now;
- curTouch._setPrevPoint(touch._prevPoint);
- locTouchIntDict[touchID] = unusedIndex;
- handleTouches.push(curTouch);
}
if (handleTouches.length > 0) {
this._glView!._convertTouchesWithScale(handleTouches);
@@ -597,7 +596,7 @@ class InputManager {
handler(event, mouseEvent, location, pos);
eventManager.dispatchEvent(mouseEvent);
- event.stopPropagation();
+ event.propagationStopped = true;
event.preventDefault();
});
};
@@ -653,7 +652,7 @@ class InputManager {
pos.left -= document.documentElement.scrollLeft;
pos.top -= document.documentElement.scrollTop;
touchEvent.call(this, [this.getTouchByXY(event.clientX, event.clientY, pos)]);
- event.stopPropagation();
+ event.propagationStopped = true;
}, false);
}
}
@@ -702,7 +701,7 @@ class InputManager {
pos.left -= body.scrollLeft || 0;
pos.top -= body.scrollTop || 0;
touchesHandler(this.getTouchesByEvent(event, pos));
- event.stopPropagation();
+ event.propagationStopped = true;
event.preventDefault();
};
};
@@ -731,12 +730,12 @@ class InputManager {
const canvas = cc.game.canvas as HTMLCanvasElement;
canvas.addEventListener('keydown', (event: KeyboardEvent) => {
eventManager.dispatchEvent(new EventKeyboard(event.keyCode, true));
- event.stopPropagation();
+ event.propagationStopped = true;
event.preventDefault();
}, false);
canvas.addEventListener('keyup', (event: KeyboardEvent) => {
eventManager.dispatchEvent(new EventKeyboard(event.keyCode, false));
- event.stopPropagation();
+ event.propagationStopped = true;
event.preventDefault();
}, false);
}
diff --git a/cocos/renderer/ui/ui.ts b/cocos/renderer/ui/ui.ts
index cae98353cd..6ebc2188c1 100644
--- a/cocos/renderer/ui/ui.ts
+++ b/cocos/renderer/ui/ui.ts
@@ -252,13 +252,14 @@ export class UI {
}
public getScreen(visibility: number) {
- this._screens.forEach((screen) => {
+ for (const screen of this._screens) {
if (screen.camera) {
if (screen.camera.visibility === visibility) {
return screen;
}
}
- })
+ }
+
return null;
}
@@ -497,13 +498,13 @@ export class UI {
if (bufferBatchIdx >= this._bufferBatches.length) {
this.createBufferBatch();
}
-
+
curBufferBatch = this._bufferBatches[bufferBatchIdx++];
vertCount = 0;
idxCount = 0;
isNewBatch = true;
}
-
+
// merge vertices
vf32 = uiRenderData.meshBuffer.vData!;
vCount = (vf32.length / this._vertF32Count);
@@ -511,16 +512,16 @@ export class UI {
if (vbSize > curBufferBatch.vbSize) {
curBufferBatch.vbCount = vCount + vertCount;
curBufferBatch.vbSize = vbSize;
-
+
const lastVF32 = curBufferBatch.vf32;
curBufferBatch.vf32 = new Float32Array(curBufferBatch.vbCount * this._vertF32Count);
if (lastVF32) {
curBufferBatch.vf32.set(lastVF32!, 0);
}
}
-
+
curBufferBatch.vf32!.set(vf32, vertCount);
-
+
// merge indices
vui16 = uiRenderData.meshBuffer.iData!;
ibSize = (vui16.length + idxCount) * 2;
@@ -534,21 +535,21 @@ export class UI {
curBufferBatch.vui16.set(lastVUI16, 0);
}
}
-
+
for (let n = 0; n < vui16.length; ++n) {
curBufferBatch.vui16![idxCount + n] = vui16[n] + vertCount;
}
-
+
curBufferBatch.vui16!.set(vui16, idxCount);
-
+
vertCount += vCount;
idxCount += vui16.length;
-
+
if (curTexView !== uiRenderData.texture.getGFXTextureView()) {
curTexView = uiRenderData.texture.getGFXTextureView();
isNewBatch = true;
}
-
+
if (isNewBatch) {
const batch = this._drawBatchPool.add();
batch.camera = curCamera;
@@ -556,7 +557,7 @@ export class UI {
batch.uiMaterial = this._uiMaterial!;
batch.texView = curTexView!;
batch.idxCount = idxCount;
-
+
this._batches.push(batch);
isNewBatch = false;
}
diff --git a/cocos/scene-graph/node-event-enum.ts b/cocos/scene-graph/node-event-enum.ts
new file mode 100644
index 0000000000..02f37e9a68
--- /dev/null
+++ b/cocos/scene-graph/node-event-enum.ts
@@ -0,0 +1,20 @@
+import { ccenum } from '../core/value-types/enum';
+
+export enum EventType {
+ TRANSFORM_CHANGED = 'transform-changed',
+ POSITION_PART = 'position-part',
+ ROTATION_PART = 'rotation-part',
+ SCALE_PART = 'scale-part',
+ TOUCH_START = 'touch-start',
+ TOUCH_MOVE = 'touch-move',
+ TOUCH_END = 'touch-end',
+ TOUCH_CANCEL = 'touch-cancel',
+ MOUSE_DOWN = 'mouse-down',
+ MOUSE_ENTER = 'mouse-enter',
+ MOUSE_MOVE = 'mouse-move',
+ MOUSE_LEAVE = 'mouse-leave',
+ MOUSE_UP = 'mouse-up',
+ MOUSE_WHEEL = 'mouse-wheel',
+}
+
+ccenum(EventType);
diff --git a/cocos/scene-graph/node-event-processor.ts b/cocos/scene-graph/node-event-processor.ts
new file mode 100644
index 0000000000..5b74582c4e
--- /dev/null
+++ b/cocos/scene-graph/node-event-processor.ts
@@ -0,0 +1,601 @@
+import { Node } from "./node";
+import { eventManager } from '../core/platform/event-manager';
+import EventTarget from '../core/event/event-target';
+import { EventListener } from "../core/platform/event-manager/CCEventListener";
+import { array } from '../core/utils/js';
+import { EventMouse, EventTouch} from "../core/platform/event-manager/index";
+import { EventType } from "./node-event-enum";
+
+const _cachedArray = new Array(16);
+_cachedArray.length = 0;
+let _currentHovered: Node | null = null;
+
+const _touchEvents = [
+ EventType.TOUCH_START.toString(),
+ EventType.TOUCH_MOVE.toString(),
+ EventType.TOUCH_END.toString(),
+ EventType.TOUCH_CANCEL.toString(),
+];
+
+const _mouseEvents = [
+ EventType.MOUSE_DOWN.toString(),
+ EventType.MOUSE_ENTER.toString(),
+ EventType.MOUSE_MOVE.toString(),
+ EventType.MOUSE_LEAVE.toString(),
+ EventType.MOUSE_UP.toString(),
+ EventType.MOUSE_WHEEL.toString(),
+];
+
+const _touchStartHandler = function (touch, event: EventTouch) {
+ const pos = touch.getLocation();
+ const node = this.owner;
+
+ if (node.uiTransfromComp.isHit(pos, this)) {
+ event.type = EventType.TOUCH_START.toString();
+ event.touch = touch;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ return true;
+ }
+ return false;
+};
+const _touchMoveHandler = function (touch, event: EventTouch) {
+ const node = this.owner;
+ event.type = EventType.TOUCH_MOVE.toString();
+ event.touch = touch;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+};
+const _touchEndHandler = function (touch, event: EventTouch) {
+ const pos = touch.getLocation();
+ const node = this.owner;
+
+ if (node.uiTransfromComp.isHit(pos, this)) {
+ event.type = EventType.TOUCH_END.toString();
+ } else {
+ event.type = EventType.TOUCH_CANCEL.toString();
+ }
+ event.touch = touch;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+};
+const _touchCancelHandler = function (touch, event: EventTouch) {
+ const node = this.owner;
+
+ event.type = EventType.TOUCH_CANCEL.toString();
+ event.touch = touch;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+};
+
+const _mouseDownHandler = function (event: EventMouse) {
+ const pos = event.getLocation();
+ const node = this.owner;
+
+ if (node.uiTransfromComp.isHit(pos, this)) {
+ event.type = EventType.MOUSE_DOWN.toString();
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ }
+};
+const _mouseMoveHandler = function (event: EventMouse) {
+ const pos = event.getLocation();
+ const node = this.owner;
+ const hit = node.uiTransfromComp.isHit(pos, this);
+ if (hit) {
+ if (!this._previousIn) {
+ // Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification
+ if (_currentHovered && _currentHovered!.eventProcessor.mouseListener) {
+ event.type = EventType.MOUSE_LEAVE;
+ _currentHovered!.dispatchEvent(event);
+ if (_currentHovered!.eventProcessor.mouseListener) {
+ _currentHovered!.eventProcessor.mouseListener!._previousIn = false;
+ }
+ }
+ _currentHovered = this.owner;
+ event.type = EventType.MOUSE_ENTER.toString();
+ node.dispatchEvent(event);
+ this._previousIn = true;
+ }
+ event.type = EventType.MOUSE_MOVE.toString();
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ } else if (this._previousIn) {
+ event.type = EventType.MOUSE_LEAVE.toString();
+ node.dispatchEvent(event);
+ this._previousIn = false;
+ _currentHovered = null;
+ } else {
+ // continue dispatching
+ return;
+ }
+
+ // Event processed, cleanup
+ // event.propagationStopped = true;
+ event.propagationStopped = true;
+};
+const _mouseUpHandler = function (event: EventMouse) {
+ const pos = event.getLocation();
+ const node = this.owner;
+
+ if (node.uiTransfromComp.isHit(pos, this)) {
+ event.type = EventType.MOUSE_UP.toString();
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ // event.propagationStopped = true;
+ event.propagationStopped=true;
+ }
+};
+const _mouseWheelHandler = function (event: EventTouch) {
+ const pos = event.getLocation();
+ const node = this.owner;
+
+ if (node.uiTransfromComp!.isHit(pos, this)) {
+ event.type = EventType.MOUSE_WHEEL.toString();
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ // event.propagationStopped = true;
+ event.propagationStopped=true;
+ }
+};
+
+function _doDispatchEvent(owner: Node, event: EventTouch) {
+ let target, i;
+ event.target = owner;
+
+ // Event.CAPTURING_PHASE
+ _cachedArray.length = 0;
+ owner.eventProcessor._getCapturingTargets(event.type, _cachedArray);
+ // capturing
+ event.eventPhase = 1;
+ for (i = _cachedArray.length - 1; i >= 0; --i) {
+ target = _cachedArray[i];
+ if (target._capturingListeners) {
+ event.currentTarget = target;
+ // fire event
+ target._capturingListeners.emit(event.type, event, _cachedArray);
+ // check if propagation stopped
+ if (event.propagationStopped) {
+ _cachedArray.length = 0;
+ return;
+ }
+ }
+ }
+ _cachedArray.length = 0;
+
+ // Event.AT_TARGET
+ // checks if destroyed in capturing callbacks
+ event.eventPhase = 2;
+ event.currentTarget = owner;
+ if (owner.eventProcessor.capturingListeners) {
+ owner.eventProcessor.capturingListeners.emit(event.type, event);
+ }
+ if (!event.propagationImmediateStopped && owner.eventProcessor.bubblingListeners) {
+ owner.eventProcessor.bubblingListeners.emit(event.type, event);
+ }
+
+ if (!event.propagationStopped && event.bubbles) {
+ // Event.BUBBLING_PHASE
+ owner.eventProcessor._getBubblingTargets(event.type, _cachedArray);
+ // propagate
+ event.eventPhase = 3;
+ for (i = 0; i < _cachedArray.length; ++i) {
+ target = _cachedArray[i];
+ if (target._bubblingListeners) {
+ event.currentTarget = target;
+ // fire event
+ target._bubblingListeners.emit(event.type, event);
+ // check if propagation stopped
+ if (event.propagationStopped) {
+ _cachedArray.length = 0;
+ return;
+ }
+ }
+ }
+ }
+ _cachedArray.length = 0;
+}
+
+function _searchMaskInParent(node: Node | null) {
+ var Mask = cc.MaskComponent;
+ if (Mask) {
+ let index = 0;
+ for (let curr = node; curr && Node.isNode(curr); curr = curr.parent, ++index) {
+ if (curr.getComponent(Mask)) {
+ return {
+ index: index,
+ node: curr
+ };
+ }
+ }
+ }
+ return null;
+}
+
+function _checkListeners(listeners: EventTarget, events) {
+ if (listeners) {
+ for (let i = 0; i < events.length; ++i) {
+ if (listeners.hasEventListener(events[i])) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+}
+
+export class NodeEventProcessor {
+ public get node(){
+ return this._node;
+ }
+ // Event listeners
+ public bubblingListeners: EventTarget | null = null;
+ public capturingListeners: EventTarget | null = null;
+ // Touch event listener
+ public touchListener: EventListener | null = null;
+ // Mouse event listener
+ public mouseListener: EventListener | null = null;
+
+ private _node: Node;
+
+ constructor(node: Node) {
+ this._node = node;
+ }
+
+ // EVENT TARGET
+
+ public _checknSetupSysEvent(type) {
+ let newAdded = false;
+ let forDispatch = false;
+ if (_touchEvents.indexOf(type) !== -1) {
+ if (!this.touchListener) {
+ this.touchListener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true,
+ owner: this._node,
+ mask: _searchMaskInParent(this._node),
+ onTouchBegan: _touchStartHandler,
+ onTouchMoved: _touchMoveHandler,
+ onTouchEnded: _touchEndHandler,
+ onTouchCancelled: _touchCancelHandler,
+ });
+ eventManager.addListener(this.touchListener as EventListener, this._node);
+ newAdded = true;
+ }
+ forDispatch = true;
+ } else if (_mouseEvents.indexOf(type) !== -1) {
+ if (!this.mouseListener) {
+ this.mouseListener = cc.EventListener.create({
+ event: cc.EventListener.MOUSE,
+ _previousIn: false,
+ owner: this._node,
+ mask: _searchMaskInParent(this._node),
+ onMouseDown: _mouseDownHandler,
+ onMouseMove: _mouseMoveHandler,
+ onMouseUp: _mouseUpHandler,
+ onMouseScroll: _mouseWheelHandler,
+ });
+ eventManager.addListener(this.mouseListener as EventListener, this._node);
+ newAdded = true;
+ }
+ forDispatch = true;
+ }
+ if (newAdded && !this._node.activeInHierarchy) {
+ cc.director.getScheduler().schedule(() => {
+ if (!this._node.activeInHierarchy) {
+ eventManager.pauseTarget(this);
+ }
+ }, this, 0, 0, 0, false);
+ }
+ return forDispatch;
+ }
+
+ /**
+ * !#en
+ * Register a callback of a specific event type on Node.
+ * Use this method to register touch or mouse event permit propagation based on scene graph,
+ * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
+ * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
+ * 2. At target phase: dispatch to the listeners of the real target
+ * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
+ * In any moment of the dispatching process, it can be stopped via `event.propagationStopped = true` or `event.stopPropagationImmidiate()`.
+ * It's the recommended way to register touch/mouse event for Node,
+ * please do not use cc.eventManager directly for Node.
+ * You can also register custom event and use `emit` to trigger custom event on Node.
+ * For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
+ * You can also pass event callback parameters with `emit` by passing parameters after `type`.
+ * !#zh
+ * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
+ * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
+ * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
+ * 2. 目标阶段:派发给目标节点的监听器。
+ * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。
+ * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
+ * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
+ * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
+ * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表
+ * @method on
+ * @param {String|Node.EventType} type - A string representing the event type to listen for.
See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.
+ * @param {Function} callback - The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique).
+ * @param {Event|any} [callback.event] event or first argument when emit
+ * @param {any} [callback.arg2] arg2
+ * @param {any} [callback.arg3] arg3
+ * @param {any} [callback.arg4] arg4
+ * @param {any} [callback.arg5] arg5
+ * @param {Object} [target] - The target (this object) to invoke the callback, can be null
+ * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
+ * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
+ * @typescript
+ * on(type: string, callback: T, target?: any, useCapture?: boolean): T
+ * @example
+ * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass.
+ * this.node.on(cc.Node.EventType.TOUCH_START, callback, this);
+ * this.node.on(cc.Node.EventType.ANCHOR_CHANGED, callback);
+ */
+ public on(type: string, callback: Function, target?: Object, useCapture?: Object) {
+ const forDispatch = this._checknSetupSysEvent(type);
+ if (forDispatch) {
+ return this._onDispatch(type, callback, target, useCapture);
+ } else {
+ // switch (type) {
+ // case EventType.POSITION_CHANGED:
+ // this._eventMask |= POSITION_ON;
+ // break;
+ // case EventType.SCALE_CHANGED:
+ // this._eventMask |= SCALE_ON;
+ // break;
+ // case EventType.ROTATION_CHANGED:
+ // this._eventMask |= ROTATION_ON;
+ // break;
+ // case EventType.SIZE_CHANGED:
+ // this._eventMask |= SIZE_ON;
+ // break;
+ // case EventType.ANCHOR_CHANGED:
+ // this._eventMask |= ANCHOR_ON;
+ // break;
+ // }
+ if (!this.bubblingListeners) {
+ this.bubblingListeners = new EventTarget();
+ }
+ return this.bubblingListeners.on(type, callback, target);
+ }
+ }
+
+ /**
+ * !#en
+ * Register an callback of a specific event type on the Node,
+ * the callback will remove itself after the first time it is triggered.
+ * !#zh
+ * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。
+ *
+ * @method once
+ * @param {String} type - A string representing the event type to listen for.
+ * @param {Function} callback - The callback that will be invoked when the event is dispatched.
+ * The callback is ignored if it is a duplicate (the callbacks are unique).
+ * @param {Event|any} [callback.event] event or first argument when emit
+ * @param {any} [callback.arg2] arg2
+ * @param {any} [callback.arg3] arg3
+ * @param {any} [callback.arg4] arg4
+ * @param {any} [callback.arg5] arg5
+ * @param {Object} [target] - The target (this object) to invoke the callback, can be null
+ * @typescript
+ * once(type: string, callback: T, target?: any, useCapture?: boolean): T
+ * @example
+ * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback);
+ */
+ once(type: string, callback: Function, target: Object, useCapture?: Object) {
+ let forDispatch = this._checknSetupSysEvent(type);
+ let eventType_hasOnceListener = '__ONCE_FLAG:' + type;
+
+ let listeners: EventTarget | null = null;
+ if (forDispatch && useCapture) {
+ listeners = this.capturingListeners = this.capturingListeners || new EventTarget();
+ }
+ else {
+ listeners = this.bubblingListeners = this.bubblingListeners || new EventTarget();
+ }
+
+ let hasOnceListener = listeners!.hasEventListener(eventType_hasOnceListener, callback, target);
+ if (!hasOnceListener) {
+ let self = this;
+ let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) {
+ self.off(type, onceWrapper, target);
+ listeners.remove(eventType_hasOnceListener, callback, target);
+ callback.call(this._node, arg1, arg2, arg3, arg4, arg5);
+ };
+ this.on(type, onceWrapper, target);
+ listeners.add(eventType_hasOnceListener, callback, target);
+ }
+ }
+
+ public _onDispatch(type: string, callback: Function, target?: Object, useCapture?: Object) {
+ // Accept also patameters like: (type, callback, useCapture)
+ if (typeof target === 'boolean') {
+ useCapture = target;
+ target = undefined;
+ } else { useCapture = !!useCapture; }
+ if (!callback) {
+ cc.errorID(6800);
+ return;
+ }
+
+ let listeners: EventTarget | null = null;
+ if (useCapture) {
+ listeners = this.capturingListeners = this.capturingListeners || new EventTarget();
+ } else {
+ listeners = this.bubblingListeners = this.bubblingListeners || new EventTarget();
+ }
+
+ if (!listeners.hasEventListener(type, callback, target)) {
+ listeners.add(type, callback, target);
+
+ if (target && target.__eventTargets) {
+ target.__eventTargets.push(this);
+ }
+ }
+
+ return callback;
+ }
+
+ /**
+ * !#en
+ * Removes the callback previously registered with the same type, callback, target and or useCapture.
+ * This method is merely an alias to removeEventListener.
+ * !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。
+ * @method off
+ * @param {String} type - A string representing the event type being removed.
+ * @param {Function} [callback] - The callback to remove.
+ * @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed
+ * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
+ * @example
+ * this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this);
+ * node.off(cc.Node.EventType.TOUCH_START, callback, this.node);
+ * node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this);
+ */
+ public off(type: string, callback: Function, target?: Object, useCapture?: Object) {
+ const touchEvent = _touchEvents.indexOf(type) !== -1;
+ const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1;
+ if (touchEvent || mouseEvent) {
+ this._offDispatch(type, callback, target, useCapture);
+
+ if (touchEvent) {
+ if (this.touchListener && !_checkListeners(this.touchListener, _touchEvents)) {
+ eventManager.removeListener(this.touchListener);
+ this.touchListener = null;
+ }
+ } else if (mouseEvent) {
+ if (this.mouseListener && !_checkListeners(this.mouseListener, _mouseEvents)) {
+ eventManager.removeListener(this.mouseListener);
+ this.mouseListener = null;
+ }
+ }
+ } else if (this.bubblingListeners) {
+ this.bubblingListeners.off(type, callback, target);
+
+ const hasListeners = this.bubblingListeners.hasEventListener(type);
+ // All listener removed
+ // if (!hasListeners) {
+ // switch (type) {
+ // case EventType.POSITION_CHANGED:
+ // this._eventMask &= ~POSITION_ON;
+ // break;
+ // case EventType.SCALE_CHANGED:
+ // this._eventMask &= ~SCALE_ON;
+ // break;
+ // case EventType.ROTATION_CHANGED:
+ // this._eventMask &= ~ROTATION_ON;
+ // break;
+ // case EventType.SIZE_CHANGED:
+ // this._eventMask &= ~SIZE_ON;
+ // break;
+ // case EventType.ANCHOR_CHANGED:
+ // this._eventMask &= ~ANCHOR_ON;
+ // break;
+ // }
+ // }
+ }
+ }
+
+ public _offDispatch(type: string, callback: Function, target?: Object, useCapture?: Object) {
+ // Accept also patameters like: (type, callback, useCapture)
+ if (typeof target === 'boolean') {
+ useCapture = target;
+ target = undefined;
+ } else { useCapture = !!useCapture; }
+ if (!callback) {
+ this.capturingListeners && this.capturingListeners.removeAll(type);
+ this.bubblingListeners && this.bubblingListeners.removeAll(type);
+ } else {
+ const listeners = useCapture ? this.capturingListeners : this.bubblingListeners;
+ if (listeners) {
+ listeners.remove(type, callback, target);
+
+ if (target && target.__eventTargets) {
+ array.fastRemove(target.__eventTargets, this);
+ }
+ }
+
+ }
+ }
+
+ /**
+ * !#en
+ * Trigger an event directly with the event name and necessary arguments.
+ * !#zh
+ * 通过事件名发送自定义事件
+ *
+ * @method emit
+ * @param {String} type - event type
+ * @param {*} [arg1] - First argument in callback
+ * @param {*} [arg2] - Second argument in callback
+ * @param {*} [arg3] - Third argument in callback
+ * @param {*} [arg4] - Fourth argument in callback
+ * @param {*} [arg5] - Fifth argument in callback
+ * @example
+ *
+ * eventTarget.emit('fire', event);
+ * eventTarget.emit('fire', message, emitter);
+ */
+ public emit(type, ...args: any[]) {
+ if (this.bubblingListeners) {
+ this.bubblingListeners.emit(type, ...args);
+ }
+ }
+
+ /**
+ * !#en
+ * Dispatches an event into the event flow.
+ * The event target is the EventTarget object upon which the dispatchEvent() method is called.
+ * !#zh 分发事件到事件流中。
+ *
+ * @method dispatchEvent
+ * @param {Event} event - The Event object that is dispatched into the event flow
+ */
+ public dispatchEvent(event: EventTouch) {
+ _doDispatchEvent(this._node, event);
+ _cachedArray.length = 0;
+ }
+
+ /**
+ * Get all the targets listening to the supplied type of event in the target's capturing phase.
+ * The capturing phase comprises the journey from the root to the last node BEFORE the event target's node.
+ * The result should save in the array parameter, and MUST SORT from child nodes to parent nodes.
+ *
+ * Subclasses can override this method to make event propagable.
+ * @method _getCapturingTargets
+ * @private
+ * @param {String} type - the event type
+ * @param {Array} array - the array to receive targets
+ * @example {@link cocos2d/core/event/_getCapturingTargets.js}
+ */
+ _getCapturingTargets(type, array) {
+ var parent = this._node.parent;
+ while (parent) {
+ if (parent.eventProcessor.capturingListeners && parent.eventProcessor.capturingListeners.hasEventListener(type)) {
+ array.push(parent);
+ }
+ parent = parent.parent;
+ }
+ }
+
+ /**
+ * Get all the targets listening to the supplied type of event in the target's bubbling phase.
+ * The bubbling phase comprises any SUBSEQUENT nodes encountered on the return trip to the root of the tree.
+ * The result should save in the array parameter, and MUST SORT from child nodes to parent nodes.
+ *
+ * Subclasses can override this method to make event propagable.
+ * @method _getBubblingTargets
+ * @private
+ * @param {String} type - the event type
+ * @param {Array} array - the array to receive targets
+ */
+ _getBubblingTargets(type, array) {
+ var parent = this._node.parent;
+ while (parent) {
+ if (parent.eventProcessor.bubblingListeners && parent.eventProcessor.bubblingListeners.hasEventListener(type)) {
+ array.push(parent);
+ }
+ parent = parent.parent;
+ }
+ }
+}
diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts
index f3d2749b21..d22c65a988 100644
--- a/cocos/scene-graph/node.ts
+++ b/cocos/scene-graph/node.ts
@@ -1,217 +1,20 @@
import { UITransformComponent } from '../3d/ui/components/ui-transfrom-component';
-import { ccclass, mixins, property } from '../core/data/class-decorator';
-import { DefaultEventTarget, EventTarget } from '../core/event/event-target-base';
-import { Enum, Mat4, Quat, Vec3 } from '../core/value-types';
+import { ccclass, property } from '../core/data/class-decorator';
+import { Mat4, Quat, Vec3 } from '../core/value-types';
import Size from '../core/value-types/size';
import Vec2 from '../core/value-types/vec2';
import { mat4, quat, vec3 } from '../core/vmath';
import { BaseNode } from './base-node';
import { Layers } from './layers';
import { WidgetComponent } from '../3d/ui/components/widget-component';
+// import { EventTarget } from '../core/event/event-target-base';
+import { NodeEventProcessor } from './node-event-processor';
+import { EventType } from './node-event-enum';
const v3_a = new Vec3();
const v3_b = new Vec3();
const q_a = new Quat();
const array_a = new Array(10);
-const _cachedArray = new Array(16);
-_cachedArray.length = 0;
-
-const EventType = Enum({
- TRANSFORM_CHANGED: 'transform-changed',
- POSITION_PART: 1,
- ROTATION_PART: 2,
- SCALE_PART: 4,
- TOUCH_START: 'touch-start',
- TOUCH_MOVE: 'touch-move',
- TOUCH_END: 'touch-end',
- TOUCH_CANCEL: 'touch-cancel',
- MOUSE_DOWN: 'mouse-down',
- MOUSE_ENTER: 'mouse-enter',
- MOUSE_MOVE: 'mouse-move',
- MOUSE_LEAVE: 'mouse-leave',
- MOUSE_UP: 'mouse-up',
- MOUSE_WHEEL: 'mouse-wheel',
-});
-
-const _touchEvents = [
- EventType.TOUCH_START,
- EventType.TOUCH_MOVE,
- EventType.TOUCH_END,
- EventType.TOUCH_CANCEL,
-];
-const _mouseEvents = [
- EventType.MOUSE_DOWN,
- EventType.MOUSE_ENTER,
- EventType.MOUSE_MOVE,
- EventType.MOUSE_LEAVE,
- EventType.MOUSE_UP,
- EventType.MOUSE_WHEEL,
-];
-
-const _touchStartHandler = function (touch, event) {
- const pos = touch.getLocation();
- const node = this.owner;
-
- if (node._hitTest(pos, this)) {
- event.type = EventType.TOUCH_START;
- event.touch = touch;
- event.bubbles = true;
- node.dispatchEvent(event);
- return true;
- }
- return false;
-};
-const _touchMoveHandler = function (touch, event) {
- const node = this.owner;
- event.type = EventType.TOUCH_MOVE;
- event.touch = touch;
- event.bubbles = true;
- node.dispatchEvent(event);
-};
-const _touchEndHandler = function (touch, event) {
- const pos = touch.getLocation();
- const node = this.owner;
-
- if (node._hitTest(pos, this)) {
- event.type = EventType.TOUCH_END;
- } else {
- event.type = EventType.TOUCH_CANCEL;
- }
- event.touch = touch;
- event.bubbles = true;
- node.dispatchEvent(event);
-};
-const _touchCancelHandler = function (touch, event) {
- const node = this.owner;
-
- event.type = EventType.TOUCH_CANCEL;
- event.touch = touch;
- event.bubbles = true;
- node.dispatchEvent(event);
-};
-
-const _mouseDownHandler = function (event) {
- const pos = event.getLocation();
- const node = this.owner;
-
- if (node._hitTest(pos, this)) {
- event.type = EventType.MOUSE_DOWN;
- event.bubbles = true;
- node.dispatchEvent(event);
- }
-};
-const _mouseMoveHandler = function (event) {
- const pos = event.getLocation();
- const node = this.owner;
- const hit = node._hitTest(pos, this);
- if (hit) {
- if (!this._previousIn) {
- // Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification
- if (_currentHovered && _currentHovered._mouseListener) {
- event.type = EventType.MOUSE_LEAVE;
- _currentHovered.dispatchEvent(event);
- _currentHovered._mouseListener._previousIn = false;
- }
- _currentHovered = this.owner;
- event.type = EventType.MOUSE_ENTER;
- node.dispatchEvent(event);
- this._previousIn = true;
- }
- event.type = EventType.MOUSE_MOVE;
- event.bubbles = true;
- node.dispatchEvent(event);
- } else if (this._previousIn) {
- event.type = EventType.MOUSE_LEAVE;
- node.dispatchEvent(event);
- this._previousIn = false;
- _currentHovered = null;
- } else {
- // continue dispatching
- return;
- }
-
- // Event processed, cleanup
- event.stopPropagation();
-};
-const _mouseUpHandler = function (event) {
- const pos = event.getLocation();
- const node = this.owner;
-
- if (node._hitTest(pos, this)) {
- event.type = EventType.MOUSE_UP;
- event.bubbles = true;
- node.dispatchEvent(event);
- event.stopPropagation();
- }
-};
-const _mouseWheelHandler = function (event) {
- const pos = event.getLocation();
- const node = this.owner;
-
- if (node._hitTest(pos, this)) {
- event.type = EventType.MOUSE_WHEEL;
- event.bubbles = true;
- node.dispatchEvent(event);
- event.stopPropagation();
- }
-};
-
-function _doDispatchEvent (owner, event) {
- let target, i;
- event.target = owner;
-
- // Event.CAPTURING_PHASE
- _cachedArray.length = 0;
- owner._getCapturingTargets(event.type, _cachedArray);
- // capturing
- event.eventPhase = 1;
- for (i = _cachedArray.length - 1; i >= 0; --i) {
- target = _cachedArray[i];
- if (target._capturingListeners) {
- event.currentTarget = target;
- // fire event
- target._capturingListeners.emit(event.type, event, _cachedArray);
- // check if propagation stopped
- if (event._propagationStopped) {
- _cachedArray.length = 0;
- return;
- }
- }
- }
- _cachedArray.length = 0;
-
- // Event.AT_TARGET
- // checks if destroyed in capturing callbacks
- event.eventPhase = 2;
- event.currentTarget = owner;
- if (owner._capturingListeners) {
- owner._capturingListeners.emit(event.type, event);
- }
- if (!event._propagationImmediateStopped && owner._bubblingListeners) {
- owner._bubblingListeners.emit(event.type, event);
- }
-
- if (!event._propagationStopped && event.bubbles) {
- // Event.BUBBLING_PHASE
- owner._getBubblingTargets(event.type, _cachedArray);
- // propagate
- event.eventPhase = 3;
- for (i = 0; i < _cachedArray.length; ++i) {
- target = _cachedArray[i];
- if (target._bubblingListeners) {
- event.currentTarget = target;
- // fire event
- target._bubblingListeners.emit(event.type, event);
- // check if propagation stopped
- if (event._propagationStopped) {
- _cachedArray.length = 0;
- return;
- }
- }
- }
- }
- _cachedArray.length = 0;
-}
enum NodeSpace {
LOCAL,
@@ -219,8 +22,8 @@ enum NodeSpace {
}
@ccclass('cc.Node')
-@mixins(EventTarget)
-class Node extends EventTarget(BaseNode) {
+// @mixins(EventTarget)
+class Node extends BaseNode {
public static EventType = EventType;
public static NodeSpace = NodeSpace;
@@ -257,8 +60,7 @@ class Node extends EventTarget(BaseNode) {
protected _matDirty = false;
protected _eulerDirty = false;
- protected _bubblingListeners: EventTarget|null = null;
- protected _capturingListeners: EventTarget | null = null;
+ protected _eventProcessor: NodeEventProcessor;
@property({
type: Vec3,
@@ -349,9 +151,13 @@ class Node extends EventTarget(BaseNode) {
this.uiTransfromComp.anchorY = value;
}
+ get eventProcessor(){
+ return this._eventProcessor;
+ }
+
constructor (name: string) {
super(name);
- // EventTarget.call(this);
+ this._eventProcessor = new NodeEventProcessor(this);
}
// ===============================
@@ -362,7 +168,6 @@ class Node extends EventTarget(BaseNode) {
* invalidate all children after relevant events
*/
public onRestore () {
- super.onRestore();
this.invalidateChildren();
}
@@ -980,321 +785,26 @@ class Node extends EventTarget(BaseNode) {
this.uiTransfromComp.setContentSize(size, height);
}
- // EVENT TARGET
+ // Event
- public _checknSetupSysEvent (type) {
- let newAdded = false;
- let forDispatch = false;
- if (_touchEvents.indexOf(type) !== -1) {
- if (!this._touchListener) {
- this._touchListener = cc.EventListener.create({
- event: cc.EventListener.TOUCH_ONE_BY_ONE,
- swallowTouches: true,
- owner: this,
- mask: _searchMaskInParent(this),
- onTouchBegan: _touchStartHandler,
- onTouchMoved: _touchMoveHandler,
- onTouchEnded: _touchEndHandler,
- onTouchCancelled: _touchCancelHandler,
- });
- eventManager.addListener(this._touchListener, this);
- newAdded = true;
- }
- forDispatch = true;
- } else if (_mouseEvents.indexOf(type) !== -1) {
- if (!this._mouseListener) {
- this._mouseListener = cc.EventListener.create({
- event: cc.EventListener.MOUSE,
- _previousIn: false,
- owner: this,
- mask: _searchMaskInParent(this),
- onMouseDown: _mouseDownHandler,
- onMouseMove: _mouseMoveHandler,
- onMouseUp: _mouseUpHandler,
- onMouseScroll: _mouseWheelHandler,
- });
- eventManager.addListener(this._mouseListener, this);
- newAdded = true;
- }
- forDispatch = true;
- }
- if (newAdded && !this._activeInHierarchy) {
- cc.director.getScheduler().schedule(function () {
- if (!this._activeInHierarchy) {
- eventManager.pauseTarget(this);
- }
- }, this, 0, 0, 0, false);
- }
- return forDispatch;
+ public on(type: string | EventType, callback: Function, target?: Object, useCapture?: any) {
+ this._eventProcessor.on(type,callback,target,useCapture);
}
- /**
- * !#en
- * Register a callback of a specific event type on Node.
- * Use this method to register touch or mouse event permit propagation based on scene graph,
- * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
- * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
- * 2. At target phase: dispatch to the listeners of the real target
- * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
- * In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.
- * It's the recommended way to register touch/mouse event for Node,
- * please do not use cc.eventManager directly for Node.
- * You can also register custom event and use `emit` to trigger custom event on Node.
- * For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
- * You can also pass event callback parameters with `emit` by passing parameters after `type`.
- * !#zh
- * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
- * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
- * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
- * 2. 目标阶段:派发给目标节点的监听器。
- * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。
- * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
- * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
- * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
- * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表
- * @method on
- * @param {String|Node.EventType} type - A string representing the event type to listen for.
See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.
- * @param {Function} callback - The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique).
- * @param {Event|any} [callback.event] event or first argument when emit
- * @param {any} [callback.arg2] arg2
- * @param {any} [callback.arg3] arg3
- * @param {any} [callback.arg4] arg4
- * @param {any} [callback.arg5] arg5
- * @param {Object} [target] - The target (this object) to invoke the callback, can be null
- * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
- * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
- * @typescript
- * on(type: string, callback: T, target?: any, useCapture?: boolean): T
- * @example
- * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass.
- * node.on(cc.Node.EventType.TOUCH_START, callback, this);
- * node.on(cc.Node.EventType.TOUCH_MOVE, callback, this);
- * node.on(cc.Node.EventType.TOUCH_END, callback, this);
- * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this);
- * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback);
- */
- public on (type, callback, target, useCapture?: number) {
- const forDispatch = this._checknSetupSysEvent(type);
- if (forDispatch) {
- return this._onDispatch(type, callback, target, useCapture);
- } else {
- // switch (type) {
- // case EventType.POSITION_CHANGED:
- // this._eventMask |= POSITION_ON;
- // break;
- // case EventType.SCALE_CHANGED:
- // this._eventMask |= SCALE_ON;
- // break;
- // case EventType.ROTATION_CHANGED:
- // this._eventMask |= ROTATION_ON;
- // break;
- // case EventType.SIZE_CHANGED:
- // this._eventMask |= SIZE_ON;
- // break;
- // case EventType.ANCHOR_CHANGED:
- // this._eventMask |= ANCHOR_ON;
- // break;
- // }
- if (!this._bubblingListeners) {
- this._bubblingListeners = new DefaultEventTarget();
- }
- return this._bubblingListeners.on(type, callback, target);
- }
+ public off(type: string, callback: Function, target?: Object, useCapture?: any) {
+ this._eventProcessor.off(type,callback,target,useCapture);
}
- // /**
- // * !#en
- // * Register an callback of a specific event type on the Node,
- // * the callback will remove itself after the first time it is triggered.
- // * !#zh
- // * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。
- // *
- // * @method once
- // * @param {String} type - A string representing the event type to listen for.
- // * @param {Function} callback - The callback that will be invoked when the event is dispatched.
- // * The callback is ignored if it is a duplicate (the callbacks are unique).
- // * @param {Event|any} [callback.event] event or first argument when emit
- // * @param {any} [callback.arg2] arg2
- // * @param {any} [callback.arg3] arg3
- // * @param {any} [callback.arg4] arg4
- // * @param {any} [callback.arg5] arg5
- // * @param {Object} [target] - The target (this object) to invoke the callback, can be null
- // * @typescript
- // * once(type: string, callback: T, target?: any, useCapture?: boolean): T
- // * @example
- // * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback);
- // */
- // once(type, callback, target, useCapture) {
- // let forDispatch = this._checknSetupSysEvent(type);
- // let eventType_hasOnceListener = '__ONCE_FLAG:' + type;
-
- // let listeners = null;
- // if (forDispatch && useCapture) {
- // listeners = this._capturingListeners = this._capturingListeners || new DefaultEventTarget();
- // }
- // else {
- // listeners = this._bubblingListeners = this._bubblingListeners || new DefaultEventTarget();
- // }
-
- // let hasOnceListener = listeners.hasEventListener(eventType_hasOnceListener, callback, target);
- // if (!hasOnceListener) {
- // let self = this;
- // let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) {
- // self.off(type, onceWrapper, target);
- // listeners.remove(eventType_hasOnceListener, callback, target);
- // callback.call(this, arg1, arg2, arg3, arg4, arg5);
- // };
- // this.on(type, onceWrapper, target);
- // listeners.add(eventType_hasOnceListener, callback, target);
- // }
- // }
-
- public _onDispatch (type, callback, target, useCapture) {
- // Accept also patameters like: (type, callback, useCapture)
- if (typeof target === 'boolean') {
- useCapture = target;
- target = undefined;
- } else { useCapture = !!useCapture; }
- if (!callback) {
- cc.errorID(6800);
- return;
- }
-
- let listeners = null;
- if (useCapture) {
- listeners = this._capturingListeners = this._capturingListeners || new DefaultEventTarget();
- } else {
- listeners = this._bubblingListeners = this._bubblingListeners || new DefaultEventTarget();
- }
-
- if (!listeners.hasEventListener(type, callback, target)) {
- listeners.add(type, callback, target);
-
- if (target && target.__eventTargets) {
- target.__eventTargets.push(this);
- }
- }
-
- return callback;
+ public once(type, callback, target, useCapture) {
+ this._eventProcessor.once(type, callback, target, useCapture);
}
- /**
- * !#en
- * Removes the callback previously registered with the same type, callback, target and or useCapture.
- * This method is merely an alias to removeEventListener.
- * !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。
- * @method off
- * @param {String} type - A string representing the event type being removed.
- * @param {Function} [callback] - The callback to remove.
- * @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed
- * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
- * @example
- * this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this);
- * node.off(cc.Node.EventType.TOUCH_START, callback, this.node);
- * node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this);
- */
- public off (type, callback, target, useCapture?: number) {
- const touchEvent = _touchEvents.indexOf(type) !== -1;
- const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1;
- if (touchEvent || mouseEvent) {
- this._offDispatch(type, callback, target, useCapture);
-
- if (touchEvent) {
- if (this._touchListener && !_checkListeners(this, _touchEvents)) {
- eventManager.removeListener(this._touchListener);
- this._touchListener = null;
- }
- } else if (mouseEvent) {
- if (this._mouseListener && !_checkListeners(this, _mouseEvents)) {
- eventManager.removeListener(this._mouseListener);
- this._mouseListener = null;
- }
- }
- } else if (this._bubblingListeners) {
- this._bubblingListeners.off(type, callback, target);
-
- const hasListeners = this._bubblingListeners.hasEventListener(type);
- // All listener removed
- // if (!hasListeners) {
- // switch (type) {
- // case EventType.POSITION_CHANGED:
- // this._eventMask &= ~POSITION_ON;
- // break;
- // case EventType.SCALE_CHANGED:
- // this._eventMask &= ~SCALE_ON;
- // break;
- // case EventType.ROTATION_CHANGED:
- // this._eventMask &= ~ROTATION_ON;
- // break;
- // case EventType.SIZE_CHANGED:
- // this._eventMask &= ~SIZE_ON;
- // break;
- // case EventType.ANCHOR_CHANGED:
- // this._eventMask &= ~ANCHOR_ON;
- // break;
- // }
- // }
- }
- }
-
- public _offDispatch (type, callback, target, useCapture) {
- // Accept also patameters like: (type, callback, useCapture)
- if (typeof target === 'boolean') {
- useCapture = target;
- target = undefined;
- } else { useCapture = !!useCapture; }
- if (!callback) {
- this._capturingListeners && this._capturingListeners.removeAll(type);
- this._bubblingListeners && this._bubblingListeners.removeAll(type);
- } else {
- const listeners = useCapture ? this._capturingListeners : this._bubblingListeners;
- if (listeners) {
- listeners.remove(type, callback, target);
-
- if (target && target.__eventTargets) {
- js.array.fastRemove(target.__eventTargets, this);
- }
- }
-
- }
- }
-
- /**
- * !#en
- * Trigger an event directly with the event name and necessary arguments.
- * !#zh
- * 通过事件名发送自定义事件
- *
- * @method emit
- * @param {String} type - event type
- * @param {*} [arg1] - First argument in callback
- * @param {*} [arg2] - Second argument in callback
- * @param {*} [arg3] - Third argument in callback
- * @param {*} [arg4] - Fourth argument in callback
- * @param {*} [arg5] - Fifth argument in callback
- * @example
- *
- * eventTarget.emit('fire', event);
- * eventTarget.emit('fire', message, emitter);
- */
public emit (type, ...args: any[]) {
- if (this._bubblingListeners) {
- this._bubblingListeners.emit(type, ...args);
- }
+ this._eventProcessor.emit(type, ...args);
}
- /**
- * !#en
- * Dispatches an event into the event flow.
- * The event target is the EventTarget object upon which the dispatchEvent() method is called.
- * !#zh 分发事件到事件流中。
- *
- * @method dispatchEvent
- * @param {Event} event - The Event object that is dispatched into the event flow
- */
public dispatchEvent (event) {
- _doDispatchEvent(this, event);
- _cachedArray.length = 0;
+ this._eventProcessor.dispatchEvent(event);
}
}