`createClient` for modularity
by James Greene
HTML
<h1>`createClient` for Modularity</h1>
JavaScript
/* Core module */
function ZeroClipboard() {
if (typeof ZeroClipboard.createClient === "function") {
return ZeroClipboard.createClient.apply(this, arguments);
}
}
ZeroClipboard.Core = {
setPendingText: function(text) {
// TODO: Set `text` for Flash
}
};
/* Core and/or other modules that add `ZeroClipboard.prototype.*` methods */
ZeroClipboard.prototype.setText = function(text) {
ZeroClipboard.Core.setPendingText(text);
return this;
};
/* Client module */
// EXTREMELY IMPORTANT
// This instance must be created before the `ZeroClipboard.Client` function is defined
var ZC_ClientProto = new ZeroClipboard();
var ZeroClipboard_Client = function (val1, val2) {
console.log("instanceof Client? " + (this instanceof ZeroClipboard_Client));
console.log("instanceof ZC? " + (this instanceof ZeroClipboard));
for (var i = 0, len = arguments.length; i < len; i++) {
console.log("arg " + i + " = " + JSON.stringify(arguments[i]));
}
}
// EXTREMELY IMPORTANT
// This will ensure that the `Client` instance gets all of the `ZeroClipboard.prototype.*` methods
ZeroClipboard_Client.prototype = ZC_ClientProto;
// EXTREMELY IMPORTANT
// This will ensure that the `Client` instances understand their inheritance structure
ZeroClipboard_Client.prototype.constructor = ZeroClipboard.Client;
var zcClients = [];
ZeroClipboard.createClient = function(val1, val2) {
// EXTREMELY IMPORTANT
// Enforce that the constructor is called with the `new` operator.
// This allows the arguments to be determined by the author of `ZeroClipboard.Client`.
var client = new ZeroClipboard_Client(val1, val2);
// Store the client instance for future iteration, exploration, `destroy` calls, etc.
zcClients.push(client);
return client;
};
/* Actual usage */
var client = new ZeroClipboard("foo", "bar");
client.setText("blah");