Month: October 2012

JavaScript Class Augmenter

Following my yesterday’s post about JavaScript inheritance without constructors, here’s another small class that exposes an easy to use API for inheritance and class augmentation. Below is the source code of the class, and the use cases are included in the distribution.

(function() {
    "use strict";

   /*
    * @namespace AcidJs
    **/
    if(undefined === window.AcidJs) {
        window.AcidJs = {};
    }

   /*
    * @class Augmenter
    * @constructor
    **/
    function Augmenter() {}

    Augmenter.prototype = {

       /*
        * @method methods Inherit methods from one class to another
        * @pulic
        * @param superclass {Class}
        * @param subclass {Class}
        * @param members {Array} [optional] Array of methods that should be inherited. If not set, all superclass methods will be copied to the subclass
        **/
        methods: function(superclass, subclass, members) {
            var
                member;

            if(members) {
                for(var i = 0; i < members.length; i ++) {
                    member = members[i];

                    if(superclass.prototype.hasOwnProperty(member)) {
                        subclass.prototype[member] = superclass.prototype[member];
                    }
                }
            } else {
                for(member in superclass.prototype) {
                    if(superclass.prototype.hasOwnProperty(member)) {
                        subclass.prototype[member] = superclass.prototype[member];
                    }
                }
            }
        },

       /*
        * @properties properties Inherit properties from one class to another
        * @pulic
        * @param superclass {Class}
        * @param subclass {Class}
        * @param properties {Array} [optional] Array of properties that should be inherited. If not set all superclass properties will be copied to the subclass
        **/
        properties: function(superclass, subclass, properties) {
            if(properties) {
                for(var i = 0; i < properties.length; i ++) {
                    if(superclass.hasOwnProperty(properties[i])) {
                        subclass[properties[i]] = superclass[properties[i]];
                    }
                }
            } else {
                   for(var property in superclass) {
                       if(superclass.hasOwnProperty(property)) {
                           subclass[property] = superclass[property];
                       }
                   }
            }
        }
    };

    window.AcidJs.Augmenter = Augmenter;
})();

Related Posts

Advertisements

JavaScript Inheritance Without Constructors

Here’s a cool way for extending JavaScript objects without using constructors and “classes”, but simple literals/singletons, representing Base and Subclass objects:

(function() {
    "use strict";

    // the extend function
    function extend(superclass, subclass) {
        for(var key in superclass) {
            if(superclass.hasOwnProperty(key)) {
                subclass[key] = superclass[key];
            }
        }
    }

    // Base object
    var
        Base = {
            props: {
                firstName: "Martin",
                lastName: "Ivanov",
                web: {
                    site: "http://wemakesites.net",
                    blog: "https://acidmartin.wordpress.com/",
                    ui: "https://acidmartin.wordpress.com/",
                    twitter: "https://twitter.com/#!/wemakesitesnet"
                }
            },
            init: function() {
                window.console.log(">>> Base.init()");
            },
            getProperties: function() {
                return this.props;
            }
        };

    // directly call Base method if required
    Base.init();

    // inheriting object with some default methods
    var
        Subclass = {
            ownMethod: function() {
                window.console.log(">>> Subclass.ownMethod()");
            }
        };

    // extend the Subclass with properties from the Base object
    extend(Base, Subclass);

    // call some methods from the Subclass
    Subclass.init();
    Subclass.ownMethod();
    window.console.log(Subclass.getProperties());
})();

Related Posts

JavaScript Wrapper for the HTML5 WebWorkers API

According to the WHATWG specifications, Web Workers allow for concurrent execution of the browser threads and one or more JavaScript threads running in the background. The browser which follows a single thread of execution will have to wait on JavaScript programs to finish executing before proceeding and this may take significant time which the programmer may like to hide from the user. It allows for the browser to continue with normal operation while running in the background.

Here’s a tiny JavaScript class for easy usage of the Workers API of HTML5. As of October 2012 Workers are supported by Firefox, Chrome, Opera, Safari and Internet Explorer 10. On older versions of IE, the class will not initialize.

After you have downloaded the class, please, make sure you check the comments in the script file to learn how to use the class.

So… Here we go:

The AcidJs.WebWorkers Class

(function() {
    "use strict";

    /*
     * @namespace AcidJs
    **/
    if(undefined === window.AcidJs) {
        window.AcidJs = {};
    }

   /*
    * @class WebWorkers
    * @constructor
    * @author Martin Ivanov http://acidjs.wemakesites.net
    **/
    function WebWorkers() {
        if(typeof(window.Worker) === "undefined") {
            var
                fn = (function(){});

            for(var o in this) {
                if(Object.hasOwnProperty(o)) {
                    this[o] = fn;
                }
            }
        }
    }

    WebWorkers.prototype = {

       /*
        * @method create Create new WebWorker
        * @public
        * @param config {Object}
        * {
        *  name: {String},
        *  script: {URL},
        *  onMessage: {Function},
        * }
        **/
        create: function(config) {
            var
                name = config.name,
                script = config.script,
                onmessage = config.onMessage;

            if(undefined === config || undefined !== this[name]) {
                return;
            }

            this[name] = new Worker(script);
            this._bind(name, onmessage);
        },

       /*
        * @method getWorker Return Worker instance
        * @public
        * @param name {String}
        * @return XrayWrapper|undefined
        **/
        getWorker: function(config) {
            return this[config.name];
        },

       /*
        * @method start execute a Worker
        * @public
        * @param config {Object}
        * {
        *  name: {String}
        * }
        **/
        start: function(config) {
            var
                name = this.getWorker({name: config.name});

            if(undefined !== name) {
                name.postMessage(config.data);
            }
        },

       /*
        * @method stop terminate a Worker
        * @public
        * @param config {Object}
        * {
        *  name: {String}
        * }
        **/
        stop: function(config) {
            var
                name = this.getWorker({name: config.name});

            if(undefined !== name) {
                name.terminate();
            }
        },

       /*
        * @method destroy Stop and delete the instance of a Worker
        * @public
        * @param config {Object}
        * {
        *  name: {String}
        * }
        **/
        destroy: function(config) {
            var
                name = config.name;

            if(undefined !== this.getWorker({name: config.name})) {
                this.stop({
                    name: config.name
                });
                delete this[config.name];
            }
        },

       /*
        * @method _bind Attach handler to the onmessage event of the Worker
        * @private
        * @param name {String}
        * @onmessage {Function}
        * @data {Object|String}
        **/
        _bind: function(name, onmessage) {
            this[name].addEventListener("message", function(e) {
                onmessage.call(this, e.data);
            }, false);
        }
    };

    window.AcidJs.WebWorkers = WebWorkers;
})();

Using the Class

(function() {
    // instantiate the class
    window.workers = new AcidJs.WebWorkers();

    // create a worker
    window.workers.create({
        script: "AcidJs.WebWorkers/workers/process-guitars.js",
        name: "process-guitars",
        onMessage: function(data) {
            console.log(data);
        }
    });

    // start the worker, post a message to it and supply some data to be processed in the background
    window.workers.start({
        name: "process-guitars",
        data: ["schecter", "fender", "gibson", "jackson", "b.c. rich", "esp", "ibanez", "charvel"]
    });

    // get the worker
    // console.log(window.workers.getWorker({name: "process-guitars"}));

    // stop the worker
    // window.workers.stop({name: "process-guitars"});

    // destroy the worker
    // window.workers.destroy({name: "process-guitars"});
})();

Did you check the demo the class? Did you enjoy the blogpost? If you did, follow me @wemakesitesnet, check my personal website or acid.js web.ui for more cool stuff.

Related Posts

Useful JavaScript Classes and Functions

  • Crossbrowser image reflections enabler JavaScript class.
  • JavaScript Mapper Class for RESTFul Methods – Recently I had to work with a bunch of RESTFul API methods, so instead of defining manually separate calls/methods for each API request, I decided to do it viceversa – to force JavaScript to create these methods automatically for me out of the RESTFul API by providing the URLS and other required data.
  • XML to JSON JavaScript Objectifier Class – Simple XML to JSON objectifier. It can be used with custom or public XML, REST APIs such as Last.FM, RSS and ATOM feeds, sitemaps, etc by converting the XML server responses to native JSON objects in the browser which are then instantly accessible by its simple to use JavaScript methods.
  • URI to JSON Serializer Class – Tiny JavaScript class, using the HTMLAnchorElement interface to convert URI string into a JSON object.  The object returned by the function contains hash, host, hostname, parameters key-value map, pathname, port and protocol. Works with all major browsers (Firefox, Chrome, Safari, Opera, IE6-10).
  • IMDB Fetcher – Experimental IMDB JavaScript and PHP API – Makes possible the execution of cross-domain AJAX queries to IMDB and returns a JSON data object for the requested movie. What is currently supported – movie title, poster, release date, description, actor(s), director(s), IMDB and MPAA rating, running time, etc.
  • Quick and Dirty Localization With JavaScript – A quick and dirty JavaScript localization routine that provides basic localization (no support for plurals, etc), operates on the DOM of the page and uses data-lang attribute for language keys storage. Lokalizr works with all major browsers, beginning with IE8.
  • JavaScript Instance Name Finder – Small JavaScript function that checks for instances of an object within a defined scope and returns an array of instances’ variable names that can be used for different purposes.
  • HTML5 Placeholder Enabler – The solution presented in this post checks for the availability of the placeholder attribute in textboxes, and if it is not available applies its content as value to the elements that contain it.
  • HTML 5 Details Element Enabler – According to WhatWG, the “<details /> element represents a disclosure widget from which the user can obtain additional information or controls“. In brief, you can use it to create panelbar elements without JavaScript, as the expand / collapse functionality is native to it. Currently (October, 2011), the only browser which supports <details /> is Google Chrome, so if you are eager to start using this element on your pages, you can do so with the help of a few lines of JavaScript to make sure it works on all browsers.
  • WebWorkers JavaScript class.
  • Classless JavaScript inheritance.
  • JavaScript class augmenter.
  • JavaScript API for TinyURL.
  • HTML Validation Bookmarklet.
  • JavaScript Template Engine.