electron/lib/common/api/callbacks-registry.js

67 lines
1.6 KiB
JavaScript
Raw Normal View History

'use strict'
2016-01-15 22:31:23 +00:00
const v8Util = process.atomBinding('v8_util')
2016-01-12 02:40:23 +00:00
2016-01-15 22:31:23 +00:00
class CallbacksRegistry {
constructor () {
this.nextId = 0
this.callbacks = {}
2016-01-12 02:40:23 +00:00
}
add (callback) {
2016-01-14 18:35:29 +00:00
// The callback is already added.
var filenameAndLine, id, location, match, ref, regexp, stackString
id = v8Util.getHiddenValue(callback, 'callbackId')
2016-01-12 02:40:23 +00:00
if (id != null) {
return id
2016-01-12 02:40:23 +00:00
}
id = ++this.nextId
2016-01-12 02:40:23 +00:00
2016-01-14 18:44:21 +00:00
// Capture the location of the function and put it in the ID string,
// so that release errors can be tracked down easily.
regexp = /at (.*)/gi
2016-03-29 00:35:49 +00:00
stackString = (new Error()).stack
2016-01-12 02:40:23 +00:00
while ((match = regexp.exec(stackString)) !== null) {
location = match[1]
2016-01-12 02:40:23 +00:00
if (location.indexOf('(native)') !== -1) {
continue
2016-01-12 02:40:23 +00:00
}
2016-03-31 16:26:11 +00:00
if (location.indexOf('electron.asar') !== -1) {
continue
2016-01-12 02:40:23 +00:00
}
ref = /([^\/^\)]*)\)?$/gi.exec(location)
filenameAndLine = ref[1]
break
2016-01-12 02:40:23 +00:00
}
this.callbacks[id] = callback
v8Util.setHiddenValue(callback, 'callbackId', id)
v8Util.setHiddenValue(callback, 'location', filenameAndLine)
return id
2016-01-15 22:31:23 +00:00
}
2016-01-12 02:40:23 +00:00
get (id) {
var ref
return (ref = this.callbacks[id]) != null ? ref : function () {}
2016-01-15 22:31:23 +00:00
}
2016-01-12 02:40:23 +00:00
call (id, ...args) {
var ref
return (ref = this.get(id)).call.apply(ref, [global].concat(args))
2016-01-15 22:31:23 +00:00
}
2016-01-12 02:40:23 +00:00
apply (id, ...args) {
var ref
return (ref = this.get(id)).apply.apply(ref, [global].concat(args))
2016-01-15 22:31:23 +00:00
}
2016-01-12 02:40:23 +00:00
remove (id) {
const callback = this.callbacks[id]
if (callback) {
v8Util.deleteHiddenValue(callback, 'callbackId')
delete this.callbacks[id]
}
2016-01-15 22:31:23 +00:00
}
}
2016-01-12 02:40:23 +00:00
module.exports = CallbacksRegistry