functionaddForm(formInstance) { if(!implements(formInstance, 'Composite', 'FormItem') { thrownewError("Object does not implement a required interface."); } ... }
// The implements function, which checks to see if an object declares // that itimplaments the required interfaces.
functionimplements(object) { // Looping through all arguments after the first one. for(var i = 1; i < arguments.length; i++) { var interfaceName = arguments[i]; var interfaceFound = false; for(var j = 0; j < object.implementsInterfaces.length; j++) { if(object.implementsInterfaces[j] === interfaceName) { interfaceFound = true; break; } } if(!interfaceFound) { returnfalse; // An interface was not found. } } }
var Composite = new Interface('Composite', ['add', 'remove', 'getChild']); var FormItem = new Interface('FormItem', ['save']);
// CompositeForm class
var CompositeForm = function(id, method, action) { ... };
...
functionaddForm(formInstance) { ensureImplements(formInstance, Composite, FormItem); // This function will throw an error if a required method is not implemented. ... }
var Interface = function(name, methods) { if(arguments.length != 2) { thrownewError("Interface constructor called with " + arguments.length + " arguments, but expected exactly 2."); }
if(typeof name !== "string") { thrownewError("Interface constructor expects name to be passed in as a string."); } this.name = name; this.methods = []; for(var i = 0; i < methods.length; i++) { if(typeof methods[i] !== "string") { thrownewError("Interface constructor expects method names to be passed in as a string."); } this.methods.push(methods[i]); } }
// Static class method.
Interface.ensureImplements = function(object) { if(arguments.length < 2) { thrownewError("Function Interface.ensureImplements called with " + arguments.length + " arguments, but expected at least 2."); }
for(var i = 1; i < arguments.length; i++) { var interface = arguments[i]; if(interface.constructor !== Interface) { thrownewError("Function Interface.ensureImplements expects arguments two and above to be instances of Interface."); } for(var j = 0; j < interface.methods.length; j ++) { var method = interface.methods[j]; if(!object[method] || typeof object[method] !== "function") { thrownewError("Function Interface.ensureImplements: object does not implement the " + interface.name + " interface. Method " + method + " was not found."); } } } }