JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://code.jquery.com/qunit/qunit-1.12.0.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.12.0.css">
<div id="qunit"></div>
<div id="qunit-fixture"></div>
JavaScript
!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);
}
});
using (
new DisposableAction(function() { console.log("::dispose() called."); }),
function(da) { console.log("body of work"); }
);
}(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."; }); }
);
});