Skip to content

Instantly share code, notes, and snippets.

@Antaris
Last active February 6, 2021 19:47
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save Antaris/7869718 to your computer and use it in GitHub Desktop.
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/
!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, _);
!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, _);
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