Last active
February 6, 2021 19:47
-
-
Save Antaris/7869718 to your computer and use it in GitHub Desktop.
A C#-like dispose pattern implemented in javascript - with underscorejs and qunit. Testable: http://jsfiddle.net/52CnZ/14/
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
!function(root, _, undefined) { | |
var Disposable = root.Disposable = function() { | |
this.disposed = false; | |
}; | |
Disposable.prototype = { | |
_dispose: function() { | |
if (!this.disposed) { | |
this.dispose(); | |
this.disposed = true; | |
} | |
}, | |
dispose: function() {} | |
}; | |
var using = root.using = function(context, disposable, action) { | |
if (arguments.length === 2) { | |
action = disposable; | |
disposable = context; | |
} | |
if (!_.isFunction(action)) | |
throw "No delegate specified for disposable instance."; | |
if (!disposable["_dispose"]) | |
throw "Instance is not disposable."; | |
try { | |
action.apply(context, [disposable]); | |
} finally { | |
disposable._dispose(); | |
} | |
}; | |
}(this, _); |
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
!function(root, _, undefined) { | |
var DisposableAction = root.DisposableAction = function(action) { | |
if (!_.isFunction(action)) | |
throw "Specified action is not a function"; | |
this.action = action; | |
}; | |
_.extend(DisposableAction.prototype, Disposable.prototype, { | |
dispose: function() { | |
this.action.call(this); | |
} | |
}); | |
}(this, _); |
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
module("using"); | |
test("Disposable pattern ensures delegate action is called with no error", function() { | |
expect(2); | |
using ( | |
new DisposableAction(function() { ok(true); }), | |
function(da) { ok(true); } | |
); | |
}); | |
test("Disposable pattern ensures delegate action is called with error", function() { | |
expect(2); | |
using ( | |
new DisposableAction(function() { ok(true); }), | |
function(da) { throws(function() { throw "An error has occured here."; }); } | |
); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment