UNPKG

esf-javascript-core

Version:

EsFramework Javascript core. Contains simple classloader, heavily inspired by ExtJs

149 lines (126 loc) 2.65 kB
/** * @type {Object} */ var Esf = require('./esf-core.js'); /* * Class definition example */ console.log("# Example class definition"); Esf.define('A', { a: null, constructor: function (a) { // Save var this.a = a; // Heyho console.log('A'); }, foo: function (b) { console.log('foo - ' + b); } }); Esf.define('B', { b: null, constructor: function (a, b) { // Call super constructor this.callParent(a); // Save var this.b = b; // Heyho console.log('B'); }, foo: function () { this.callParent('bar'); } }, { extend: 'A' }); // Use var b = new B(1, 2); // or var b = Esf.create('B', 1, 2); /* * Output: * A * B * foo - bar */ b.foo(); /* * Output: * A * B * foo - bar */ b.foo(); /** * Singletons */ console.log("# Example singletons"); Esf.define('Some.Namespace.Foo', { bar: function () { console.log('bar'); } }, { singleton: true }); // Output: bar Some.Namespace.Foo.bar(); /* * Tagged classes example * you musn't use singletons, you could also use normal classes they must be initialized while iterating */ console.log("# Example tagged classes"); Esf.define('Esf.Serializer.Encoder.C', { supports: function (format) { return format == 'json'; }, deserialize: function (string, reviver) { return JSON.parse(string, reviver); }, serialize: function (data, reviver) { return JSON.stringify(data, reviver); } }, { tags: ['esf_serializer.encoder'], singleton: true }); // Find encoders var encoders = Esf.findTaggedClasses('esf_serializer.encoder'), result; if (encoders.length == 0) throw "no encoders were found"; for (var key in encoders) { // Get encoder (as we defined a singelton returns otherwise class prototype ) var encoder = encoders[key]; if (encoder.supports('json')) { result = encoder.deserialize('{"success":true}'); break; } } // outputs true console.log(result.success); /* * Private classes example */ console.log("# Example Private classes"); Esf.define('Example', function () { // Create private class prototype var PrivateException = Esf.define({ constructor: function (msg) { return this.callParent("Exception in Example: " + msg); } }, { extend: 'Error' }); // Example return { foo: function () { throw new PrivateException("bar"); } }; }); try { new Example().foo(); } catch (e) { console.log("Catched Exception: " + e); }