Skip to content

Instantly share code, notes, and snippets.

@swvitaliy
Forked from addyosmani/gist:1057989
Last active December 31, 2015 20:09
Show Gist options
  • Save swvitaliy/8038461 to your computer and use it in GitHub Desktop.
Save swvitaliy/8038461 to your computer and use it in GitHub Desktop.
define(function() {
// https://gist.github.com/addyosmani/1057989
/**
Code copyright Dustin Diaz and Ross Harmes, Pro JavaScript Design Patterns.
**/
// Constructor.
var Interface = function(name, methods) {
if (arguments.length !== 2) {
throw new Error("Interface constructor called with " + arguments.length + "arguments, but expected exactly 2.");
}
this.name = name;
this.methods = [];
for (var i in methods) {
if (methods.hasOwnProperty(i)) {
if (typeof i !== 'string' || typeof methods[i] !== 'object' ||
methods[i].constructor.toString().substr(9, 7) !== 'Array()') {
throw new Error("Interface constructor expects method to be " +
"passed in as a key value pairs.");
}
this.methods[i] = methods[i];
}
}
};
Interface.DEBUG = true;
Interface.OBJECT_PROPERTY = true;
Interface.PROPERTY_KEY = 'interfaces';
var ifIndex = 0;
// Static class method.
Interface.ensureImplements = function(ifaces, object) {
if (Interface.OBJECT_PROPERTY) {
object[Interface.PROPERTY_KEY] = [];
}
for (var i = 0, len = ifaces.length; i < len; i++) {
var iface = ifaces[i];
if (iface.constructor !== Interface) {
iface = new Interface('__' + ifIndex, iface);
}
for (var method in iface.methods) {
if (iface.methods.hasOwnProperty(method)) {
var args = iface.methods[method];
if (!object[method] || typeof object[method] !== 'function') {
throw new Error("Function Interface.ensureImplements: object " +
"does not implement the " + iface.name + " interface. Method " + method + " was not found.");
}
if (Interface.DEBUG) {
object[method] = (function(method, args) {
return function() {
for (var i = 0; i < args.length; i += 1) {
if (arguments.length <= i || !(arguments[i] instanceof args[i])) {
throw new Error("Called method \"" + method +
"\" - argument #" + i + " not passed or has invalid type");
}
}
return this[method].apply(this, arguments);
};
})(method, args);
}
}
}
if (Interface.OBJECT_PROPERTY) {
object[Interface.PROPERTY_KEY].push(iface);
}
}
return object;
};
return Interface;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment