2016-03-25 19:41:24 +00:00
|
|
|
'use strict'
|
2016-01-15 22:31:23 +00:00
|
|
|
|
2016-03-25 19:41:24 +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 {
|
2016-03-25 19:41:24 +00:00
|
|
|
constructor () {
|
|
|
|
this.nextId = 0
|
|
|
|
this.callbacks = {}
|
2016-01-12 02:40:23 +00:00
|
|
|
}
|
|
|
|
|
2016-03-25 19:41:24 +00:00
|
|
|
add (callback) {
|
2016-01-14 18:35:29 +00:00
|
|
|
// The callback is already added.
|
2016-03-25 19:41:24 +00:00
|
|
|
var filenameAndLine, id, location, match, ref, regexp, stackString
|
|
|
|
id = v8Util.getHiddenValue(callback, 'callbackId')
|
2016-01-12 02:40:23 +00:00
|
|
|
if (id != null) {
|
2016-03-25 19:41:24 +00:00
|
|
|
return id
|
2016-01-12 02:40:23 +00:00
|
|
|
}
|
2016-03-25 19:41:24 +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.
|
2016-03-25 19:41:24 +00:00
|
|
|
regexp = /at (.*)/gi
|
|
|
|
stackString = (new Error).stack
|
2016-01-12 02:40:23 +00:00
|
|
|
while ((match = regexp.exec(stackString)) !== null) {
|
2016-03-25 19:41:24 +00:00
|
|
|
location = match[1]
|
2016-01-12 02:40:23 +00:00
|
|
|
if (location.indexOf('(native)') !== -1) {
|
2016-03-25 19:41:24 +00:00
|
|
|
continue
|
2016-01-12 02:40:23 +00:00
|
|
|
}
|
|
|
|
if (location.indexOf('atom.asar') !== -1) {
|
2016-03-25 19:41:24 +00:00
|
|
|
continue
|
2016-01-12 02:40:23 +00:00
|
|
|
}
|
2016-03-25 19:41:24 +00:00
|
|
|
ref = /([^\/^\)]*)\)?$/gi.exec(location)
|
|
|
|
filenameAndLine = ref[1]
|
|
|
|
break
|
2016-01-12 02:40:23 +00:00
|
|
|
}
|
2016-03-25 19:41:24 +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
|
|
|
|
2016-03-25 19:41:24 +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
|
|
|
|
2016-03-25 19:41:24 +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
|
|
|
|
2016-03-25 19:41:24 +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
|
|
|
|
2016-03-25 19:41:24 +00:00
|
|
|
remove (id) {
|
|
|
|
return delete this.callbacks[id]
|
2016-01-15 22:31:23 +00:00
|
|
|
}
|
|
|
|
}
|
2016-01-12 02:40:23 +00:00
|
|
|
|
2016-03-25 19:41:24 +00:00
|
|
|
module.exports = CallbacksRegistry
|