How to build a simple app

Pink is a Javascript framework to build single page apps, we'll show you how to get started with a simple tutorial based on the "Image search" sample app.

Application structure

      +App
      +--ImageSearch
      +----Search
      |------lib.js
      |------tpl.html
      +----View
      |------lib.js
      |------tpl.html
      +----Shell
      |------lib.js
      |------tpl.html
      |----lib.js
      +content
      +--css
      |----pink.css
      |----tasks.css
      +--img
      +libs
      |index.html
	                    

Pink was heavly influenced from Ink's module structure and Durandal.js framework. With that foundation we built a modular structure based on conventions for the names of files and the directory tree that is used to arrange components. An app is comprised of modules, a module is a piece of UI logic that serves a single well defined purpose. Pink modules can be purely logic expressed in javascript (lib.js) or can also have an UI template (tpl.html).

index.html

At the root of the application is the main html file, in this case "index.html". This file is the only page the browser loads throught the aplication lifecycle.

    ...
    
    <body>
        <div id="applicationHost" data-bind="module: 'App.Images.Shell'"></div>
        
        <script src="libs/ink-all.js"></script>
        <script type="text/javascript">
            Ink.setPath('App', 'App/');
            Ink.setPath('Pink', 'libs/Pink/');
    
            Ink.requireModules(['App.Images'], function(app) {
                app.run();
            });        
        </script>
   </body>
</html>
                        

In the body of the page we find the div with the initial data binding directive, that tells the framework what is the first UI module to load. Usually this module has the application layout, with menus and the active route's module.

The "Ink.setPath" command defines where Ink can find the modules needed by the app, this should include the application folder (usually "App") and Pink's libraries folder (usually "libs/Pink").

After that, we find the "Ink.requireModules" command, that instructs Ink to load the needed application modules, and when the module is ready, call the application run method.

App/Images/lib.js

Ink.createModule('App.Images', '1', ['Pink.App_1', 'Pink.Plugin.Signals_1', 'Pink.Data.Binding_1'], function(App, Signal, ko) {
    var Module = function() {
        App.call(this, 'search', 'search'); 

        this.appTitle = 'Image search sample';
    };
    
    Module.prototype = new App();
    Module.constructor = Module;

    Module.prototype.listInvisibleRoutes = function() {
        return [
          {hash: 'search', module: 'App.Images.Search'},
          {hash: 'view', module: 'App.Images.View'}
        ];
    };
    
    Module.prototype.addCustomSignals = function() {
        this.signals.viewPhoto = new Signal();
    };

    Module.prototype.ready = function() {
        var self=this;
        
        Ink.requireModules(['App.Images.View'], function() {
            self.start();
        });
    };

    return new Module();
});
                        

The application module must inherit it's prototype from the "Pink.App" module. As this simple application as no visible menus, we only need to redefine the app's "listInvisibleRoutes" method that must return an array of route definitions.
A route definition matches an url fragment (hash) with a module name, this match is made through a regular expression that can have parameter placeholders.

We also override the "addCustomSignals" method from "Pink.App", this allows us to add new client signals to the app. Although not required, is's a good pratice to decouple the app's modules, so that they have very limited knowledge about the other parts of the application, allowing those parts to be easly replaced. For this decoupling we usually use custom events to signal the ocurrence of some actions, like the success of an entity save, or the change in a search widget's terms.

In this example we create a new signal called "viewPhoto" that will notify the "App.Images.View" module to show the photo's details. The photo details will be passed along with event.

The "ready" method from "Pink.App" is also overriden to add custom startup logic. In our example we require the preload of the "App.Images.View" module, so that it can subscribe to "viewPhoto" events. After that we call "Pink.App" "start" method, that begins the data binding process, in our case, loading the "App.Images.Shell" method referenced in "index.html".

App/Images/Shell/lib.js

Ink.createModule('App.Images.Shell', '1', ['App.Images'], function(app) {
    var Module = function() {
        var self=this;

        this.appTitle = app.appTitle;
        this.mainModule = app.mainModule;
        this.modalModule = app.modalModule;
        this.alertModule = app.alertModule;
        this.infoModule = app.infoModule;
    };

    Module.prototype.afterRender = function() {
        app.signals.shellRendered.dispatch();
    };

    return new Module();
});
                        

The "App.Images.Shell" module, is the main app layout were we define the app's title, the main module that is loaded from the app's current active route, and optionally modal window modules. The "afterRender" method is called by the framework after the module's template is rendered, so we use that to notify other parts of the app that the app's layout is ready.

App/Images/Shell/tpl.html

<div id="appContainer" class="ink-grid toggle no-padding">
    <div id="toastPanel"></div>
    <div id="standbyLightBox">
        <div class="lightbox-container">
            <i class="icon-spinner icon-spin icon-4x"></i>
        </div>
    </div>
    <div class="column-group">
        <nav id="mainMenu" class="ink-navigation">
            <ul class="menu horizontal white">
                <li><a href="#search"><i class="icon-home"></i></a></li>
            </ul>
            <h4 class="menu-title" data-bind="text: appTitle"></h4>
        </nav>
    
        <section data-bind="module: mainModule">
        </section>
            
        <div data-bind="module: modalModule"></div>
        <div data-bind="module: alertModule"></div>
        <div data-bind="module: infoModule"></div>
    </div>
</div>
                        

The "App.Images.Shell" template (App/Images/Shell/tpl.html), has the app's main layout markup, responsible for UI composition through the use of the "module" binding directive. Here we instruct the framework to load the active route's module (mainModule). If we want to show modal dialogs, we should also include, the "Pink.App"'s "modalModule", "alertModule" and "infoModule".

App/Images/Search/lib.js

Ink.createModule('App.Images.Search', '1', ['App.Images', 'Pink.Data.Binding', 'Ink.Net.JsonP_1'], function(app, ko, JsonP) {
    var Module = function() {
        var self=this;
        
        this.photos = ko.observableArray();
        this.noPhotos = ko.computed(function() {
            return self.photos().length==0;
        });
        this.search = ko.observable('');
        this.searching = ko.observable(false);
        
        this.search.subscribe(this.searchChangeHandler.bind(this));
    };
    
    Module.prototype.searchChangeHandler = function(search) {
        if (this.timer) {
            window.clearTimeout(this.timer);
        }
        
        if (search.length > 2) {
            this.timer = window.setTimeout(this.doSearch.bind(this, search), 1000);
        }
    };
    
    Module.prototype.doSearch = function(search) {
        var self=this;
        var uri = 'http://services.sapo.pt/Photos/JSON2?u='+search;

        this.searching(true);
        this.photos([]);
        
        new JsonP(uri, {
            params: {limit: '40'}, 
            onSuccess: function(data) {
                var aItems = data.rss.channel.item;
                var photos = [];
                var i;

                if (aItems) {
                    for(i=0, total=aItems.length; i < total; i++) {
                        photos.push({
                            tbUrl: aItems[i]['media:thumbnail'][2].url,
                            url: aItems[i]['media:content'].url,
                            title: aItems[i].title,
                            clickHandler: self.viewPhoto.bind(self)
                        });
                    }
                }
                
                self.searching(false);
                self.photos(photos);
            }, 
            onFailure: function() {
                self.searching(false);
                app.showErrorToast('Failure in photos service');
            }
        });
    };
    
    Module.prototype.viewPhoto = function(photo) {
        app.signals.viewPhoto.dispatch(photo);
    };

    return new Module();
});
                        

The 'App.Images.Search' module is the application home module, where the user can input a simple keyword query to make a search in SAPO's photo service.

When the user clicks on a photo, the module emits a "viewPhoto" signal with the selected photo.

App/Images/Search/tpl.html

<div class="half-space">
    <div class="ink-form">
        <div class="control-group column-group half-right-space">
            <div class="control">
                <input type="search" placeholder="Search terms..." data-bind="value: search, valueUpdate: 'afterkeydown'"></input>
            </div>
        </div>
    </div>
    <!-- ko if: searching  -->
        <i class="icon-spinner icon-spin icon-4x"></i>
    <!-- /ko -->
    <!-- ko ifnot: searching -->
        <div class="top-space" data-bind="foreach: photos">
            <div class="thumbnail">
                <a href="javascript:void(0)" data-bind="click: clickHandler">
                   <img data-bind="attr: {src: tbUrl}" height="120">
                </a>
            </div>
        </div>
        <div class="top-space" data-bind="visible: noPhotos">
            No results
        </div>
    <!-- /ko -->
</div>
                        

The search template binds the view model's (App/Images/Search/lib.js), "search", "searching", "photos", and "noPhotos" properties to build the home UI.

App/Images/View/lib.js

Ink.createModule('App.Images.View', '1', ['App.Images', 'Pink.Data.Binding_1'], function(app, ko) {
    var Module = function() {
        app.signals.viewPhoto.add(this.viewPhoto.bind(this));
        
        this.photoSrc = ko.observable('');
        this.photoTitle = ko.observable('');
    };
    
    
    Module.prototype.viewPhoto = function(photo) {
        this.photoSrc(photo.url);
        this.photoTitle(photo.title);
        app.navigateTo('#view');
    };

    return new Module();
});
                        

The "App.Images.View" module subscribes to "viewPhoto" signals, and when it'receives them, updates the "photoSrc" and "photoTitle" properties and tells the app to change the active route to the "view" route.

App/Images/View/tpl.html

                        
<div class="space">
    <h3 data-bind="text: photoTitle"></h3>
</div>
<div class="space">
    <img data-bind="attr: {src: photoSrc}">
</div>