Skip to content

Commit 9fb75b7

Browse files
authored
Merge pull request alibaba#2199 from MrRaindrop/html5-feature-module-event
[html5] support module event.
2 parents e756dbb + 27b6cd3 commit 9fb75b7

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
2+
/**
3+
* save the original listener for 'addEventListener'.
4+
* this is the dipaching listener which is waiting for feed.
5+
* map structure: moduleName -> eventName -> [handlers].
6+
*/
7+
const handlerMap = {}
8+
9+
window.addEventListener('moduleevent', event => {
10+
const dt = event.detail || {}
11+
const module = dt.module
12+
const type = dt.type
13+
try {
14+
handlerMap[module][type].forEach(handler => handler(dt))
15+
}
16+
catch (e) {
17+
console.warn(`[h5-render] no such event ${type} for module ${module}.`)
18+
}
19+
})
20+
21+
export function addEventListener (module, evt, callbackId, options) {
22+
const once = options && !!options.once
23+
let moduleMap = handlerMap[module]
24+
if (!moduleMap) {
25+
moduleMap = handlerMap[module] = {}
26+
}
27+
let handlers = moduleMap[evt]
28+
if (!handlers) {
29+
handlers = moduleMap[evt] = []
30+
}
31+
handlers.push((data) => this.sender.performCallback(callbackId, data, !once))
32+
}
33+
34+
export function removeAllEventListeners (module, evt) {
35+
try {
36+
delete handlerMap[module][evt]
37+
}
38+
catch (e) {
39+
// do nothing.
40+
}
41+
}

html5/render/browser/render/register.js

+23
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,28 @@ import ComponentManager from '../dom/componentManager'
22
import { registerLoader } from './loader'
33
import { protocol } from '../bridge'
44
import { extend } from '../utils'
5+
import { addEventListener, removeAllEventListeners } from '../base/moduleEvent'
6+
7+
/**
8+
* register module event listener for every api module except 'globalEvent'.
9+
*/
10+
function registerModuleEventListener (name, module, meta) {
11+
if (name !== 'globalEvent') {
12+
module['addEventListener'] = function (evt, callbackId, options) {
13+
return addEventListener.call(this, name, evt, callbackId, options)
14+
}
15+
module['removeAllEventListeners'] = function (evt) {
16+
return removeAllEventListeners.call(this, name, evt)
17+
}
18+
; [{
19+
name: 'addEventListener',
20+
args: ['string', 'function', 'object']
21+
}, {
22+
name: 'removeAllEventListeners',
23+
args: ['string']
24+
}].forEach(info => meta[name].push(info))
25+
}
26+
}
527

628
const methods = {
729
// Register a new component with the specified name.
@@ -13,6 +35,7 @@ const methods = {
1335
// If the module already exists, just add methods from the
1436
// new module to the old one.
1537
registerApiModule (name, module, meta) {
38+
registerModuleEventListener(name, module, meta)
1639
if (!protocol.apiModule[name]) {
1740
protocol.apiModule[name] = module
1841
}

0 commit comments

Comments
 (0)