Skip to content

Instantly share code, notes, and snippets.

@squallstar
Created March 2, 2012 11:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save squallstar/1957795 to your computer and use it in GitHub Desktop.
Save squallstar/1957795 to your computer and use it in GitHub Desktop.
A simple sandbox for your webapp. Includes hooks on dom ready, pubsub pattern and much more.

JS Sandbox Application

A simple sandbox for your webapp. Includes hooks on dom ready, pubsub pattern and much more.

Requires jQuery 1.7+.

#Source

/**
 * Sandbox App
 * @author: Nicholas Valbusa - @squallstar - www.squallstar.it
 *
 * Thanks to: Matteo Gildone, Marco Solazzi
 * Includes: jQuery Tiny Pub/Sub by Ben Alman

(function (window, $, undefined) {

    var App = function () {
        var self = this,
            mywidget = new Widget({app : self})
        ;

        this.hooks_cont = {};
        this.widgets = {
            mywidget : mywidget
        };
    };

    App.prototype = {
        init : function () {
            $(document).ready(function() {
                this.call_hooks();
            });
        },

        call_hooks : function (context) {
            var c = context || this, h;
            if (!this.hooks_cont) {
                return;
            }
            for (h in this.hooks_cont) {
                var $els = jQuery(h) || [];
                if ($els.length > 0) {
                    this.hooks_cont[h].call(c, h, $els);
                }
            }
        },

        hooks : function (add_hooks) {
            $.extend(this.hooks_cont, add_hooks);
        },

        subscribe : function () {
            $.on.apply($, arguments);
        },

        unsubscribe : function () {
            $.off.apply($, arguments);
        },

        publish : function () {
            $.trigger.apply($, arguments);
        }
    };

    var Widget = function (options) {
        options || (options = {});
        this.app = options.app;
    };

    Widget.prototype = {
        cheers : function () {
            //hello world
        }
    };

    window.app = new App();
    app.init();

}(window, jQuery, undefined));

How to use

Bind hooks on dom ready

app.hooks({
    "a.target" : function() {
        ....
    }
});

Subscribe:

app.subscribe('eventname', function (data) {
    ....
});

Publish:

app.publish('eventname', 'somevalue');

Use your widget:

app.widget.cheers();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment