Last active
September 20, 2015 02:10
-
-
Save SeanCline/09910d6e09412182bc4f to your computer and use it in GitHub Desktop.
A minimal Signal class that lets you connect and disconnect handlers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* File: Signal.js | |
* Classes: Signal, Signal.Connection | |
* Author: Sean Cline | |
* Version: .1 | |
* Description: A minimal Signal class that lets you connect and disconnect handlers to be called when .emit(...) is called. | |
* License: You may do whatever you please with this file and any code it contains. It is public domain. | |
* Usage: | |
* let sig = new Signal(); | |
* let connection1 = sig.connect(function(str) { alert(str + "1") }); | |
* let connection2 = sig.connect(function(str) { alert(str + "2") }); | |
* | |
* sig.emit("test"); | |
* connection2.disconnect(); | |
* sig.emit("test"); | |
* | |
* The above code will alert "test1", "test2", then "test1" again. | |
*/ | |
"use strict"; | |
class Signal { | |
constructor() { | |
this.connections_ = []; | |
} | |
emit(...params) { | |
for (let connection of this.connections_) { | |
connection.call(...params); | |
} | |
} | |
emitAsync(...params) { | |
let self = this; | |
setTimeout(function() { | |
self.emit(...params); | |
}, 0); | |
} | |
connect(func) { | |
let connection = new Signal.Connection(this, func); | |
this.connections_.push(connection); | |
return connection; | |
} | |
disconnect(connection) { | |
let index = this.connections_.indexOf(connection); | |
if (index > -1) { | |
this.connections_.splice(index, 1); | |
} | |
} | |
} | |
Signal.Connection = class { | |
constructor(signal, func) { | |
this.signal_ = signal; | |
this.func_ = func; | |
} | |
disconnect() { | |
this.signal_.disconnect(this); | |
this.signal_ = this.func_ = undefined; | |
} | |
call(...params) { | |
this.func_(...params); | |
} | |
get isConnected() { return typeof(this.func_) != 'undefined'; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment