Tag Archives: Components

Part 7: Sharing data in Knockout Components (1/2) – Building a Tree Component

Continuing my account of using KO Components and the building of the Silkthread SPA, today I am going to build another component – a Tree view component.

Note: All my articles on KO Components are now categorized and you can bookmark the this link for easy reference. All future articles will automatically appear in that list.

No one really uses a TreeView in a public facing Website today, but the underlying hierarchical data representation is still very valid and the TreeView has transformed into a series of Folding panels, cascading dropdowns, CSS Menus or in case of mobile devices cascading set of lists.

I came across the need for the TreeView because I wanted to build a Documentation Index for the SilkThread site. So this is like dog-fooding of SilkThread SPA itself. Today we’ll explore the following things:

  1. How to layout the TreeView, creating the Tree and TreeNode components (1/2).
  2. How to pass data into nested Components (we have done this in the previous article also) (1/2)
  3. Styling the TreeView (1/2)
  4. How to raise and handle events using Amplify.js (2/2)

Creating the Tree and the TreeNode components

I am starting with v6 label of my BuildingSpaWithKO project in Github.

Adding a new Page

1. First up, we’ll add a new ‘page component’ called docs.

Adding a new Page Component

a. Add new folder under App/pages called docs
b. Add a docs.js and docs.html file in the docs folder. Remove all the boilerplate code/markup that Visual Studio adds and setup the component as follows

define(['knockout', 'text!./docs.html'], function (ko, docsTemplate) {
    function docsViewModel(params) {
        var self = this;
        self.title = ko.observable('SilkThread - Yet another SPA Framework');
        self.data ={
            title: 'Documentation Home',
            nodes: []
        };
        return self;
    }
    return { viewModel: docsViewModel, template: docsTemplate };
});

The component is pretty self explanatory, it has two properties, title and data. The title property has a default text but is an observable, so if we bind it to an html element if will be updated in the UI if we decide to change the Title at runtime.

The ‘nodes’ property has an empty JavaScript object at the moment and we will pump mock data into it once our component is ready.

Registering the Docs page

To register our new page we update the app.js by adding the new page definition to it.

app = {
    components: {
        greeter: {
            name: 'greeter',
            template: 'App/components/greeter/greeting'
        },
        tabitem: {
            name: 'tabitem',
            template: 'App/components/tabitem/tabitem'
        },
        tabbedNavigation: {
            name: 'tabbed-navigation',
            template: 'App/components/tabbed-navigation/tabbed-navigation'
        }
    },
    pages: {
        home: {
            name: 'home',
            template: 'App/pages/home/home'
        },
        docs: {
            name: 'docs',
            template: 'App/pages/docs/docs'
        },
        settings: {
            name: 'settings',
            template: 'App/pages/settings/settings'
        }
    }
}

We register the component in startup.js as follows:

ko.components.register(app.pages.docs.name, { require: app.pages.docs.template });

To navigate to the ‘Docs’ page we add a link in _Layout.cshtml page. as seen below the href is pointing to the page-name we registered above.

                <ul class="nav navbar-nav">
                    <li>
                        <a href="/">Home</a>
                    </li>
                    <li>
                        <a href="settings">Settings</a>
                    </li>
                    <li>
                        <a href="docs">Docs</a>
                    </li>
                </ul>

image

Finally we add the docs route to our router in router.js as follows

    return new Router({
        routes: [
            { url: '/', params: { page: 'home' } },
            { url: 'home', params: { page: 'home' } },
            { url: 'docs', params: { page: 'docs' } },
            { url: 'samples', params: { page: 'samples' } },
            { url: 'settings', params: { page: 'settings' } }
        ]
    });

With the Docs page in place we can get down to the business of creating the actual Tree component.

Building a Tree View using KO Components

A tree component can logically have two sub-parts. First the container and second a Node object that can itself contain a list of Nodes. So we create two components for this purpose:

1. The Tree-Node component
2. The Tree component

The Tree Node Component

We look at the node view model before we look at the container. As standard with all KO Components we create a Tree folder under the Scripts/app/components folder and add two files tree-node.html and tree-node.js

The Node view model (tree-node.js)

define(["knockout", "text!./tree-node.html"], function (ko, treeNodeTemplate) {
    function treeNodeViewModel(params) {
        var self = this;
        self.title = ko.observable('Default');
        self.url = ko.observable('/');
        self.nodes = ko.observableArray();
        self.expanded = ko.observable(true);
        if (params.node) {
            self.title(params.node.title);
            if (params.node.expanded != null) {
                self.expanded(params.node.expanded);
            }
            self.nodes().push.apply(self.nodes(), params.node.nodes);
        }

        self.changeState = function () {
            self.expanded(!self.expanded());
        }
        return self;
    }
    return { viewModel: treeNodeViewModel, template: treeNodeTemplate };
});

The treeNodeViewModel has four fields and a function() to store the information and react to actions on it.

title – This is the text that’s displayed on the Node
url – A relative or absolute URL to navigate to when user clicks on the node.
nodes – A collection of more treeNodeViewModels that are child nodes of the current node. Note that, the nodes collection essentially makes the view model recursive.
expanded – A property storing the state of the current node, as to whether its child nodes are shown or hidden. This is applicable only when the nodes collection has more than one element.
changeState() – This function is attached to the click event of the span element in the view. The span has the text + or – depending on the value of ‘expanded’ property.

The Node View (tree-node.html)

The corresponding markup for the Node view is as follows:

<ul class="nav nav-stacked" style="padding-left:10px">
    <li class="nav list-group-item-heading selected">
        <div class="row">
            <div class="col-sm-1 hidden-xs">
                <!-- ko if: nodes().length > 0 -->
                <!-- ko if: expanded() -->
                <a data-bind="click: changeState" role="button" href="">
                    <i class="glyphicon-minus"></i>
                </a>
                <!-- /ko -->
                <!-- ko ifnot: expanded() -->
                <a data-bind="click: changeState" role="button" href="">
                    <i class="glyphicon-plus"></i>
                </a>
                <!-- /ko -->
                <!-- /ko -->
            </div>
            <div class="col-sm-5">
                <span data-bind="text: title"></span>
            </div>
        </div>
    </li>
    <!-- ko if: nodes().length > 0 && expanded() === true -->
    <!-- ko foreach: nodes -->
    <li>
        <tree-node params="node: $data"></tree-node>
    </li>
    <!-- /ko -->
    <!-- /ko -->
</ul>

 

The tree-node is wrapped in a <ul> just to make use of Bootstrap’s default indentation. If you want you can use any markup. The <div class=”row”> is where things get interesting. We have two columns in the row.

The first column is rendered conditionally. We check if there are elements in the nodes collection. If there are one or more nodes we check the expanded() property to see if we should render a [-] or a [+] using an anchor tag. We also attached the click event of the anchor to the changeState function.

The second column is a span that’s bound to the title property of the tree-node viewmodel.

Finally we need to render the rest of the nodes so again we check if the nodes collection is empty or not. If there are one or more nodes we loop though each node and render a tree-node itself with the current instance of the node object as provided by KO in the $data variable.

The Tree Component

Now that we have seen what the node looks like lets setup the container

The Tree view model (tree.js)

define([
    "knockout",
    "text!./tree.html"], function (ko, treeTemplate) {
    function treeViewModel(params) {
        var self = this;
        self.title = ko.observable('');
        self.nodes = ko.observableArray([]);

        if (params.data) {
            self.title(params.data.title);
            self.nodes().push.apply(self.nodes(), params.data.nodes);
        }
        return self;
    }
    return { viewModel: treeViewModel, template: treeTemplate };
});

As we can see, the viewModel is pretty simple, it has two properties:
title – A string that can be shown on top of the TreeView
nodes – A collection of node objects.

The Tree view (tree.html)

The markup for the Tree component simply binds the nodes collection from the viewModel into a unordered list.

<ul class="nav nav-stacked">
    <li class="nav list-group-item-heading" data-bind="text: title">
    	<!-- ko if: nodes().length > 0 -->
    		<li>
        	<!-- ko foreach: nodes -->
        		<tree-node params="node: $data"></tree-node>
        	<!-- /ko -->
    	<!-- /ko -->
   	</li>
</ul>

Registering the new components

We go back to the app.js file and add our two new components to the ko.components’ list.

app = {
    components: {
        greeter: {
            name: 'greeter',
            template: 'App/components/greeter/greeting'
        },
        tabitem: {
            name: 'tabitem',
            template: 'App/components/tabitem/tabitem'
        },
        tabbedNavigation: {
            name: 'tabbed-navigation',
            template: 'App/components/tabbed-navigation/tabbed-navigation'
        },
        treeNode: {
            name: 'tree-node',
            template: 'App/components/tree-node/tree-node'
        },
        tree: {
            name: 'tree',
            template: 'App/components/tree/tree'
        }
    },
    pages: {
        home: {
            name: 'home',
            template: 'App/pages/home/home'
        },
        docs: {
            name: 'docs',
            template: 'App/pages/docs/docs'
        },
        settings: {
            name: 'settings',
            template: 'App/pages/settings/settings'
        }
    }
}

 

Adding some dummy data

Now that we’ve got the components in place, let’s add some dummy data to bring up the tree. We go back to the docs.js file and update the data source.

self.data =
	{
            title: "Documentation Home",
            nodes: [
                {
                    title: "Node 0",
                    nodes: [
                    {
                        title: "Node 0-1",
                        expanded: false,
                        nodes: [
                            {
                                title: "Node 0-1-0"
                            },
                            {
                                title: "Node 0-1-1"
                            }
                        ]
                    },
                    {
                        title: "Node 0-2"
                    }]
                },
                {
                    title: "Node 1",
                    expanded: false,
                    nodes: [
                    {
                        title: "Node 1-1"
                    },
                    {
                        title: "Node 1-2"
                    }]
                },
                {
                    title: "Node 2"
                }]
        }

Demo Time

Now that we are setup with the new components lets run the app and see how it works.

Navigating to the docs page shows us the following:

image

Notice ‘Node 0-1’ and ‘Node 1’ are not expanded by default but ‘Node 0’ is. This is because these nodes have the expanded property explicitly set to false. By default expanded is assumed true.

So we have a functional Tree layout. However clicking on the nodes don’t do anything because their HREFs are empty and there is no ‘click’ handler to do something with.

Initially I wanted to introduce AmplifyJS in this article itself, but this one is already 1500+ chars and is straining on everyone’s patience. So I am going to split up this article and introduce AmplifyJS in the next article where we’ll see how we can use it to handle events and share data across components.

Tagged , , ,

Part 6: Custom Components – Tabs

In Part 4 we have seen how to use History.JS along with Crossroads.js to achieve proper client side routing and maintain browser state for proper back button navigation. However, SPAs often have complex page states for example a page with tabbed data or grid data with a particular filter.

One of the ways we can make a particular Tab of data ‘bookmark-able’ is by including the selected tab information as a part of the route. Thus, the particular tab becomes a part of the URL and can be navigated to directly or pushed to the browser history and retrieved on back button.

As you may have noted, our SPA has a name now – SilkThread and a site of it’s own http://silkthread.pw. Today we’ll create a Tab-Item component that will working with SilkThread’s routing mechanism.

Important: When I started this series KO Components was still in Beta, since then version 3.2.0 has gone live and is now available on Nuget also.This article onwards, I am using the release version from Nuget.

Before diving into custom components

We have been using ‘’magic strings” for representing routes, component names and so on. Multi-use components are used more than once, and complex views might be composed of multiple components. Relying on magic strings can be error prone and ‘difficult to maintain’. Why? Well imagine that you have created a component called drop-down in the drop-down folder. Now when you access it elsewhere you specify a magic string ‘drop-down’. But does the next person looking into your code know what it signifies? Is it the component name or the folder name or file name or just a random key? However if you accessed the string via a literal app.components.dropDown.name it will be amply clear that that string is for. So before our framework gets any more complex, let’s take a stab at cleaning up our magic strings.

The Component Registration

We add a new file called app.js in the /app folder. Mind you this is a first stab and we are likely to refactor later. Next we add the following code to it

app = {
components: {
greeter: {
name: ‘greeter’,
template: ‘App/components/greeter/greeting’
}
},
pages: {
home: {
name: ‘home’,
template: ‘App/pages/home/home’
},
settings: {
name: ‘settings’,
template: ‘App/pages/settings/settings’
}
}
}

As we can see this is a simple JS object that splits pages and components into different types and registers each sub object represents a component with two properties name and template to start off with.

Now we update our startup.js to use the appropriate component name and template names.

define([‘jquery’, ‘knockout’, ‘./router’, ‘app’, ‘bootstrap’, ‘knockout-projections’], function ($, ko, router) {
ko.components.register(
app.components.greeter.name, { require: app.components.greeter.template });

    ko.components.register(app.pages.home.name, { require: app.pages.home.template });
ko.components.register(app.pages.settings.name, { require: app.pages.settings.template });
ko.applyBindings({ route: router.currentRoute });
});

Going forward, we’ll register our components via the app.components object.

Registering with Require

We have to tell Require there is a global app object now, so we update the require.config.js and add the app/app route the list.

var require = {
baseUrl: “/”,
paths: {


“app”: “app/app”
    },

}

Getting a little JS help – Including Underscore.js

The Underscore.js library is a very handy toolset and has some nifty helper functions. I’ll explain the ones we use as I use them. To install it, just use the package-management console

PM> install-package underscore.js

The library is by default installed under the Scripts folder. I’ve moved it to the ‘Scripts\underscore’ subfolder.

image

Like the app.js earlier we’ll register Underscore in the require.config.js as well.

var require = {
baseUrl: “/”,
paths: {

“app”: “app/app”,
“underscore”: “Scripts/underscore/underscore”
},

}

With these two modifications to existing code set, we’ll start with the actual component.

Creating a Tab Component

A tab component has two parts, the tabbed header and the panel showing the tab’s content. If we consider the Tab as a menu item it could be a different page altogether. But at any given point a tab control shows only one panel, which is logically related to the selected tab.

To start off with we’ll create a component – tabbed-navigation. The tabbed-navigation component will be the top-level container that will be responsible for showing the tab headers and the selected tab’s container panel. The container panel will be a placeholder div that will be replaced by the component that needs to be shown for the selected tab. We can configure each tab to show a different component.

The tab-navigation HTML template

The HTML template in the app\components\tab-navigation\tab-navigation.html has the following markup:

<ul id=”tabHeader” class=”nav nav-tabs” role=”tablist”>
<!– ko foreach: tabs –>
<li data-bind=”css : {active : isSelected }”>
<a data-bind=”text : text, attr : { href: url }”></a>
</li>
<!– /ko –>
</ul>

<div id=”tabPanel”
data-bind=”component: {name: selected().component, params: {name: selected().text }}”></div>

It has a simple layout using <ul> and the boot-strap styling classes nav and nav-tabs.

Inside the <ul> we loop through an array of tabs items which is going to be encapsulated in the tab-navigation.js view model.

In the loop we add a <li> that has the style active if the viewModel tab’s isSelected property is set to true. This sets the active style from Bootstrap.

In the <li> we have an anchor with two data-bindings. First is the text that’s going to be shown, next the url that’s bound to the href attribute.

Finally we have the <div> tabPanel. This is bound to a component which is initialized with the name and params properties. The name is bound to the selected tab’s component property (so our viewModel has to be able to return a selected tab). In params the only parameter we are currently sending is the name property, which is again picked up from the text property of the selected ViewModel.

The tab-navigation View Model and DataSource

From the above template we can probably guess of a data structure like the following

var ds = {
tabs: [
{
text: ‘selected 0’,
url: ‘/settings/tab0’,
isSelected : true
},
{
text: ‘selected 1’,
url: ‘/settings/tab1’,
isSelected: false
},
{
text: ‘selected 2’,
url: ‘/settings/tab2’,
isSelected: false
}],
selected : function() {
// Return the tab that has isSelected = true;
}
}

To accommodate this structure we use two JS modules – tabsNavigationConfig.js and tabitemConfig.js

tabitemConfig.js

tabitemConfig = function (text, url, selected, component) {
self = this;
self.text = text;
self.url = url;
self.isSelected = selected;
self.component = component;
return self;
}

tabsNavigationConfig.js

tabsNavigationConfig = function (tabitems, selectedIndex) {
self = this;
self.tabs = [];
for (var i = 0; i < tabitems.length ; i++) {
self.tabs.push(tabitems[i]);
if (i == selectedIndex) {
self.tabs[i].isSelected = true;
}
}
return self;
}

The tabsNavigationConfig object has a constructor function that has the list of tabitemConfig objects and the index of which of the tabs is selected.

If you are still wondering as to why we are having a separate datasource for the component, it is simple. We want our component to be re-usable at multiple places, in the same page if required. Hence if we can decouple the data-source from the ViewModel we can configure any number of tab-navigation components with different data-sources. The ViewModel would only be concerned with the rendering and event handling limited to changing of the tabs.

The tab-navigation ViewModel

With the data source ready, we’ll setup the viewModel of the tab-navigation component. I have tagged each relevant line of code with an Index. You can click on them to see more details.

define([“knockout”,
        “underscore”,                                          // #1
“text!./tabbed-navigation.html”],
function (ko, _, tabbedNavigationTemplate) {                   // #2
var isInitialized = false;                                 // #3
var tabsCache = [];
var selectedIndexCache = 0;
function tabbedNavigationViewModel(params) {               // #4
self = this;
if (!isInitialized) {                                  // #5
isInitialized = true;
tabsCache = params.tabConfig().tabs;
}
self.tabs = ko.observableArray(tabsCache);             // #6
self.selectedIndex = ko.observable(selectedIndexCache);// #7
self.selected = ko.pureComputed(function () {          // #8
return self.tabs()[self.selectedIndex()];
}, this);
if (params.route) {                                    // #9
selectByRoute(params.route());
}
function selectByRoute(route) {                       // #10
var newTab = _.find(self.tabs(), function (tab) {   // #11
return tab.url == route();
});
if (newTab) {
self.tabs()[self.selectedIndex()].isSelected = false; //#12
var index = self.tabs().indexOf(newTab);      // #13
select(index);                                // #14
}
return item;                                      // #15
};
function select(index)                                // #16
{
selectedIndexCache = index;
self.tabs()[index].isSelected = true;
self.selectedIndex(index);
}
  return self;
};
return {
viewModel: tabbedNavigationViewModel,
template: tabbedNavigationTemplate };
});

#1: We start off by declaring that we refer to Underscore.js.
#2: Underscore is assigned to the variable _ Winking smile.

#3: We create three cache variables that are a part of the module rather than the viewModel constructor function. These are the list of tabs, the selected index and a flag indicating whether we have some cached information or not. When navigating to a tab we will get routed via the settings route. This will reinitialize the viewModel, so if we have the values cached we can use them instead of initializing the tabbed control everytime.

#4: The viewModel constructor function tabbedNavigationViewModel which takes in an initialization parameter, and may have a tabsConfig property. The tabsConfig has an array of tabs and the index of the selctedTab.

#5: We check if the module is being initialized the first time around. If so, we set the incoming tabs collection into the cache and mark the module as initialized.

#6: We initialize the tabs with the list in tabs cache.

#7: We set the default selectedIndex to 0.

#8: Pure Computed Observables: We have a new type of Observable introduced in KO 3.2.0 called the pureComputed. We know KO had computed observables that automatically updated themselves when their constituent observables changed. However, they suffered from one drawback. Computed observables were always triggered as soon as the constituent observables changed, even if the computed observable was not bound to a view element. This was a performance hit. To resolve this we now have pureComputed observables that get re-calculated only if they have subscriptions, i.e. someone is waiting to update itself based on changes in the pureComputed.

Here we have declared the selected property as a pureComputed and it returns the selected Tab. The selection changes whenever the selectedIndex changes. So anytime the selectedIndex changes the selected property returns the newly selected tab. As we will see in a bit, this renders a new container.

#9: We check if this viewModel is being created as a result of navigation (all cases except of first time page load). If it is due to navigation the route parameter is populated and we use it to select the particular sub-tab indicated by the route property.

#10: The selectByRoute function, called everytime the route changes.

#11: We use the Underscore library to find tab in the tabs collection. The syntax of _.find expects the array of items to look into and a comparison function to call for each element in the array. It returns the first element it finds.

#12: Once we’ve found the element we use the current selected index to set the isSelected flag to false for the current tab.

#13: We retrieve the index of the new selcted tab

#14: Next we call the select method.

#15: The select method sets the isSelected property of the new tab and updates the selectedIndexCache value for future use.

Initializing the Tab Component

Now that we’ve seen the structure of data we need and how that data is used lets see how we can use them. The Tab component is used inside the Settings Page component. So someone has to initialize it in the Settings page.

Tab Component markup in Settings.html

The markup to use the Tab Component is simple and unremarkable:

<div>
<h1>Settings</h1>
</div>
<tabbed-navigation params=”tabConfig : tabbedNavigation(), route: route()”>
</tabbed-navigation>

There are two items being passed in the params property, tabConfig and route. The tabConfig property has the initialization parameters of how many tabs, their text, their URL and so forth. Refer to the tabNavigation viewModel section above.

The binding parameters imply that the Component View Model that’s backing this HTML has to provide he tabbedNavigation and route properties.

Tab Component viewModel code

Before now, the settings component was HTML only. We introduce the backing JS for this component. The code for it is as follows:

define(
[
“knockout”,
“text!./settings.html”,
“underscore”,
“../../components/models/tabbed-navigation/tabsNavigationConfig”,
“../../components/models/tabbed-navigation/tabitemConfig”
],
function (ko, settingsTemplate, _) {
var isInitialized = false;
var tabsNavigationInstance = null;
function settingsViewModel(params) {
var self = this;
self.tabbedNavigation = new ko.observable();
if (!isInitialized) {
isInitialized = true;
tabsNavigationInstance = init(params);
}
self.tabbedNavigation(tabsNavigationInstance);
self.route = new ko.observable();
if (params.tab) {
self.route(params.request_);
}
return self;
};
function init(params) {
var newTabs = [];
for (var i = 0; i < 5; i++) {
var key = ‘tab’ + i;
newTabs.push(new tabitemConfig(
“Settings ” + i,
“/settings/” + key,
key == params.tab,
‘greeter’));
}
tabsNavigationInstance = new tabsNavigationConfig(newTabs, 0);
return tabsNavigationInstance;
}
return { viewModel: settingsViewModel, template: settingsTemplate };
});

The crux of the component view model is the init method that’s called from the constructor function first time around. It need not be called init though. This function initializes an array and pushes in 5 instances of the tabitemConfig that we defined earlier. Since this is a demo we are simply doing a loop. For a real life scenario we would instantiate each instance with a relevant name and more importantly route to a component that should be visible when the tab is selected. In our case we are setting each route to point to the previously created ‘greeter’ component. So for every tab selection we’ll show a greeter component and if you refer back to the original markup at the top you’ll see we pass the selected tabs’ text property to the greeter as a parameter. So the greeter shows name of the tab selected.

Demo time

If we run the application and navigate to the Settings page we’ll see the following

– First tab ‘Settings 0’ is selected
– Greeter is saying Hello to ‘Settings 0’

image

– Clicking on Settings 1 tab, ‘navigates to that tab.Notice the route changes to settings/tab1. This corresponds to the route we setup when initializing the tabitemConfig object.

image

Now we can click on the Browser back button to navigate back to Settings 0 tab, and go forward again to come back to Settings 1 tab. When you navigate you’ll notice that the timestamp of Greeter component keeps changing this is because the greeter component doesn’t cache the time stamp so everytime the constructor function is called, the time gets updated.

Code for this version is available on the Part6 branch of the repository https://github.com/sumitkm/BuildingSpaUsingKO/tree/Part6

Conclusion

In conclusion we saw how we could create a ‘tab-component’ using KO’s component model of development. Next we’ll see how we can use different components in different tabs and how to call server to get/put data.

Tagged , , , ,

Part 5: SPAs, Accessibility and the Server side

Part 1: Dipping your feet into KnockoutJS Components
Part 2: Knockout Components – Separating Templates from View Model
Part 3: KO Components – Routes and Hashes
Part 4: SPA with KO Components-PushState and History JS

Recap

In the previous 4 parts we have seen how to use Knockout Components to make a sample Single Page Application, with different type of client routing libraries.

Towards the end of the third article I had highlighted how SPAs hinder Accessibility and Search-ability of a site’s content primarily because:

a. Search engines don’t ‘click’ on URLs to load content, they simply follow URLs they find and request the server for content. Whatever the server returns is indexed as content of that URL.

b. Accessibility tools work on similar logic to Search engines and cannot ‘click’ on URLs to load content.

Towards both these ends we took a small first step by moving from a hash based client side router to a pushState based one that falls back gracefully for non-push state browsers. This gave us URLs that looked like /settings instead of #settings. The search engine or accessibility tool now knows it has to navigate to a new URL to get the content.

At the end of the last article I has shown how the server would return a 404 or some similar server-side error because when we click on http://buildingspausingko.azurewebsites.net/settings there is no page at that URL. Remember our entire site is being served from index.html. How to we fix this?

Enter server side routing fallbacks

Before we start let’s get the Part 4 code from Github.

Using _Layout and adding an Index.cshtml for the home page

Before anything, let’s start using the server in the first place.

Our Application was an Empty ASP.NET application to start with. So to get started we’ll first add ASP.NET MVC to it. We can do this by installing the package Microsoft.AspNet.Mvc

PM> install-package Microsoft.AspNet.Mvc

Now let’s add Controller/HomeController and a Views/Home/Index.cshtml files.

We update the Layout such that it contains the top navigation bar and then calls the RenderBody function to render the rest of the page.

<!DOCTYPE html>
<html xmlns=”
http://www.w3.org/1999/xhtml”>
<head>
<title>Dipping your feet into KnockoutJS Components</title>
<link href=”/Content/bootstrap.css” rel=”stylesheet” />
<link href=”/Content/bootstrap-theme.css” rel=”stylesheet” />
</head>
<body>
<div class=”navbar navbar-inverse navbar-fixed-top”>
<div class=”container”>
<div class=”navbar-header”>
<button type=”button” class=”navbar-toggle” data-toggle=”collapse” data-target=”.navbar-collapse”>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
</button>
<a class=”navbar-brand” href=”/”>KO Components</a>
<ul class=”nav navbar-nav”>
<li>
<a href=”/”>Home</a>
</li>
<li>
<a href=”settings”>Settings</a>
</li>
</ul>
</div>
</div>
</div>
<div id=”page1″ class=”container” style=”padding-top:50px”>
@RenderBody()
</div>
<footer class=”navbar navbar-fixed-bottom”>
<div class=”container-fluid”>
<p> &copy; 2014 – Still Learning</p>
</div>
</footer>
<script src=”App/boot/require.config.js”></script>
<script data-main=”App/boot/startup” src=”Scripts/require/require.js”></script>
</body>
</html>

We put in a simple header in the index.cshtml file showing that it is coming from the server. However not that the div containing the Index content is also the container for the dynamic component which will be loaded by Require JS.

@{
Layout = “~/Views/Shared/_Layout.cshtml”;
}
<div id=”page1″ class=”container” style=”padding-top:50px;” data-bind=”component: { name: route().page, params: route }”>
<div class=”container” style=”background-color: red”>
<h1>Index from Server</h1>
</div>
</div>

Finally, let’s rename the Index.html to Index2.html so that it’s not picked up as the default by IIS.

If you run the application now you’ll see the ‘Index from Server’ text flashes briefly before being replaced by the greetings.

This simply implies that there was a page that the server rendered and returned, once the page was loaded the client side routing kicked in and replaced the container.

This was the default page.

In the browser change URL by adding settings you’ll get an error as follows:

image

This is because there is an invalid redirection in my web.config. Open the web.config and delete the highlighted section

image

Now if you type in the URL /settings on the browser you’ll get a proper 404

image

You must be wondering how come when I click on Settings link from Home page I get a proper page, but when I type in the URL I get a 404? Well, that’s because typing in a URL sends the request to the server directly. In our case, it sends to ASP.NET MVC. MVC framework uses the current route info and tries to map it to a ‘SettingsController’ with a default ‘Index’ action method. However it doesn’t find the SettingsController and throws a 404.

This is what will happen to Search Engines and Screen readers as well. Even though they will see a URL, trying to browse to it will get them a 404. Search engines will down-rate your site and screen readers will give a poor experience to people using them.

So how do we solve this? Let’s explore two ways today.

Sending the same page back for all URLs from Server

This is a hackish technique to make sure your users can navigate to the correct page from bookmarked URLs. This doesn’t really help in Search engine optimization or screen readers. But atleast no one gets a 404 when a valid URL is accessed directly from the browser.

For this, all we have to do is, manipulate the MVC router to send all requests to HomeController’s Index action method.

Once the Index page is returned the client side router will kick in and do the ‘right thing’.

In the App_Start\RouteConfig.cs update the RegisterRoutes method as follows:

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
routes.MapRoute(
name: “Default”,
url: “{*pathinfo}”,
defaults: new { Controller=”Home”, action = “Index”, id = UrlParameter.Optional }
);
}

As you can see above, we have changed the url parameter to be a wildcard {*pathinfo}, and set the default for this wildcard path to Home Controllers’ Index action method.

If you run the application now, and navigate to the Settings page by typing in the URL you’ll see that there is no more 404 error. BUT, the client side routing seems to be taking us back to the Index page. Why?

image

Removing hard coded default path in router.js

Well, in our ‘excitement’ to get History.js going with crossroads.js in the last article, we introduced a small hardcoding that’s causing the about “BUG”.

In Router.js’ activateCrossRoads function the last line instructs crossroads to route to the root location (‘/’).

crossroads.parse(‘/’);

This is why even though the browser is pointing to settings page, the page is showing the greetings from the Index page.

Let’s fix this.

The inline function call that’s being bound to the stateChanged event actually needs to be called on first Initialization as well. So let’s refactor it out to a separate function called routeCrossroads.

function routeCrossRoads()
{
var State = History.getState();
if (State.data.urlPath) {
return crossroads.parse(State.data.urlPath);
}
else {
if (State.hash.length > 1) {
var fullHash = State.hash;
var quesPos = fullHash.indexOf(‘?’);
if (quesPos > 0) {
var hashPath = fullHash.slice(0, quesPos);
return crossroads.parse(hashPath);
}
else {
return crossroads.parse(fullHash);
}
}
else {
return crossroads.parse(‘/’);
}
}
}

I have made some changes to the code in the else section. Actually the condition to check for ‘?’ is there to handle IE9 properly. In case of IE9, History appends a state Id to the URL after ‘?’. Crossroads doesn’t need the state ID hence I strip it out. But the initial condition is incomplete because if there are no ? in the URL we need the entire path (fullHash). I have fixed this in the above code.

Once the above function is in place, the activateCrossroads function becomes as follows:

function activateCrossroads() {
History.Adapter.bind(window, “statechange”,
routeCrossRoads);
crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
//crossroads.parse(‘/’);
routeCrossRoads();
}

As we can see we have commented out the default routing to the root ‘/’.

With everything in place if we run the app now, and try to type if /settings at the end of the URL we’ll get the correct settings page.

image

But again, before the Settings page is loaded you will briefly see the red banner saying ‘Index from Server’ flash briefly before navigating to the ‘’Settings’ page. This is because for all URLs we are returning the same Index page from the Server. How do we fix this, if the answer wasn’t obvious, read on Smile

Technique 2: Sending a Server Side page for every URL

Now that our SPA is capable of responding to all URLs specified in our web app, let’s dig deeper to see how we can respond to all pages equally.

This section is experimental on my part, if there are better ways to do this, please sound off in the comments section.

Updating the MVC routing

First thing to do is to update the Routetable to add independent routes for Home/Index and (say) Settings/Index pages.

We’ll keep the ‘catch all’ route that we defined earlier so that if there are any routes that are not defined on the server but defined on the client, we send them off to the home page to load the old fashioned way.

public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);
    routes.MapRoute(
name: “Default”,
url: “{Controller}/{action}/{id}”,
defaults: new { action = “Index”, id = UrlParameter.Optional }
);

routes.MapRoute(
name: “
CatchAll“,
url: “{*pathinfo}”,
defaults: new { Controller=”Home”, action = “Index”, id = UrlParameter.Optional }
);
}

With the above routing in place, lets add a new controller called SettingsController and a new cshtml at Views/Settings/Index.cshtml

The Settings Index file again is a simple one saying it’s coming from server! It uses the _Layout.cshtml file for the header.

@{
Layout = “~/Views/Shared/_Layout.cshtml”;
}
<div id=”page1″ class=”container” style=”padding-top:50px” data-bind=”component: { name: route().page, params: route }”>
<div class=”container”>
<h1>Settings from Server</h1>
</div>
</div>

Now when we run the application and type in /settings we’ll get the server page first and then the client page will get loaded, so you’ll see a brief flash saying ‘Settings from Server’.

In real world the duplication of cshtml and html templates may be a significant effort, I am looking at making things easier in that front and will blog about it if I find anything better. As of now, if you want the best user experience for all types of users (as well as the search engine), this is an extra bit of work that you have to do. It’s not as bad as it sounds either, all you have to do is use the same service that you call during the HTTP GET operation from client, and bind that data to the CSHTML. You can skip elaborate styling and limit it to having correct markup laid out in an orderly fashion.

Code

As usual the code for this article is up on Github. I have branched this code off as Part5: https://github.com/sumitkm/BuildingSpaUsingKO/tree/Part5

Conclusion

With that we conclude this part of the series where we saw how we can handle bookmarked URLs on the server and client. This goes a long way in helping users who use accessibility tools use your site effectively.

More fine tuning will be required on the client side router to handle all scenarios but that’s for another day.

Next we’ll see how to handle URL parameters and more involved routing like Tabs.

Tagged , , , , ,

Part 3: KO Components – Routes and Hashes

Part 1: Dipping your feet into Knockout JS Components
Part 2: Knockout Components – Separating Templates from View Model

As we continue our journey to learn more about KO Components, today we look at how we can  navigate around different ‘views’ and manage hyperlinks.

There are multiple libraries out there that allow you to do this. Today we’ll see how to use Crossroads for routing and Hasher for managing URLs. They internally use the Signals JS library. All three are written by Miller Medeiros. Now you could do all things these three libraries to with Sammy.js too. I will probably look at Sammy.js at some point in future, but Sammy is more opinionated on how it does routing and event handling, while I wanted to go one level lower and fiddle around myself. BTW I am in no way promoting one over the other, just that today’s sample uses Crossroads, Hasher and Signals.

Adding dependencies

All three libraries are not available as Nuget packages so we’ve to get them from their Github Repos directly. I have linked to the repos above.

Apart from the above three we will also use knockout-projections extension library by Steve Sanderson. This provides helper methods to deal with KO arrays.

I have downloaded them and added to the solution resulting in the following folder layout:

image
Figure 1

Updating require.config.js

We update the require.config.js to add the additional references so Require knows where to get them from as and when required.

var require = {
baseUrl: “/”,
paths: {
“bootstrap”: “Scripts/bootstrap/bootstrap”,
“crossroads”: “Scripts/crossroads/crossroads”,
“jquery”: “Scripts/jquery/jquery-1.9.0”,
“knockout”: “Scripts/knockout/knockout-3.2.0beta.debug”,
“knockout-projections”: “Scripts/knockout/knockout-projections.min”,
“signals”: “Scripts/crossroads/signals”,
“hasher”: “Scripts/crossroads/hasher”,
“text”: “Scripts/require/text”
},
shim: {
“bootstrap”: {
deps: [“jquery”]
}
}
}

Restructuring the App layout and adding a page

Since we are going to demo navigation, it’s good to have at least one more page to navigate to. So we’ll introduce a loosely coupled concept of ‘page-components’. These are basically registered as ko.components but they are containers and in turn use other ko components.

As I said in my previous article the folder structure I was using is pretty arbitrary and open to updates.

Under App we will add a pages folder which will have all our ‘page’ components. I have added two, home and settings.

image
Figure 2

The home page-component

The Home page component has the standard HTML + JS structure. I have in-fact taken out the greeter instances from Index.html. We’ll see how we can pass data between two components. We’ll add a collection of ‘guests’ in home view model which will be passed to the greeter component. So our home.js will be as follows:

define([“knockout”, “text!./home.html”], function (ko, homeTemplate) {
function homeViewModel(params) {
var self = this;
self.title = ko.observable(‘Dipping your feet into KnockoutJS’);
self.guests = ko.observableArray([]);
self.guests.push({ guestName: “Sumit” });
self.guests.push({ guestName: “Optimus” });
self.guests.push({ guestName: “Bumblebee” });
return self;
}
return { viewModel: homeViewModel, template: homeTemplate };
});

We have put the header text in a property called title. We also have an observable array of guests who the greeter component needs to greet. Instead of hard-coding the names this could have come from a server API call.

The home.html is as follows

<h2 data-bind=”text: title”></h2>
<hr />
<!– ko foreach: guests –>
<greeter params=’name: guestName’></greeter>
<!– /ko –>
<pre data-bind=”text: ko.toJSON($data, null, 5)”></pre>

We have bound the title to the header element.

Next we have a standard ko foreach that loops through each element in guests collection. The params attribute takes a JSON snippet so we pass it appropriately as name: guestName. KO can evaluate the observable and pass the appropriate value to the greeter component.

Setting up Routing using Crossroads and Hasher

In Figure 2 above you’ll note we have a new file called router.js.

The Router is defined as an AMD module. It takes in an object with the property routes that has an array of routes that are ‘registered’. So the routes property is going to hold all our routes.

As of now we have defined two routes, one is the home page that is at the root of the site and the second is the settings page that should be at the /settings URL.

When the module is initialized the Router function is invoked (acts as the ‘constructor’) with the routes defined. These are added to crossroads. I have added a method to log every routing event to the console.

The activateCrossroads function sets up Hasher to listen for hash changes and on change invoke crossroads to do the routing.

/// <reference path=”/Scripts/crossroads/crossroads.js” />
define([“jquery”,”knockout”, “crossroads”, “hasher”], function ($, ko, crossroads, hasher) {

    return new Router({
routes: [
{ url: ”, params: { page: ‘home’ } },
{ url: ‘settings’, params: { page: ‘settings’ } }
]
});

    function Router(config) {
var currentRoute = this.currentRoute = ko.observable({});

        ko.utils.arrayForEach(config.routes, function (route)
{
crossroads.addRoute(route.url, function (requestParams)
{
currentRoute(ko.utils.extend(requestParams, route.params));
});
});
crossroads.routed.add(console.log, console);
activateCrossroads();
}

    function activateCrossroads() {
function parseHash(newHash, oldHash){
crossroads.parse(newHash);
}
        crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;

        hasher.initialized.add(parseHash);
hasher.changed.add(parseHash);
hasher.init();
}
});

With routing all set, let’s setup the Index page and register the new components before we can test out our changes.

Updating the Index.html page

The Index page has now become a nearly empty shell. We will add two links in the header, one for Home and the other for Settings page.

<div class=”navbar navbar-inverse navbar-fixed-top”>
<div class=”container”>
<div class=”navbar-header”>
<button type=”button” class=”navbar-toggle” data-toggle=”collapse” data-target=”.navbar-collapse”>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
<span class=”icon-bar”></span>
</button>
<a class=”navbar-brand” href=”/”>KO Components</a>
<ul class=”nav navbar-nav”>
<li>
<a href=”#”>Home</a>
                </li>
<li>
<a href=”#settings”>Settings</a>
                </li>
</ul>
</div>
</div>
</div>
<div id=”page” class=”container” style=”padding-top:50px” data-bind=”component: { name: route().page, params: route }”></div>


By default the page will land at the Home page and when user clicks on Settings the routing library will take it to the Settings page (or back to home page depending on the link clicked).

The div with id=page is our equivalent of RenderBody in MVC. The current page as defined by the route with be displayed here. As you can see it is using a div to bind any component that is presented to it by the router. If you remember we have setup two routes with page names home and settings. So these are the names of our home and page components. Let’s register them in startup.js.

Registering new components

We’ll add the two new components to startup.js and also initialize our router and pass it to ko as root view model.

To initialize router we use Require’s module loading to request for it in the required collection. Note the syntax ./router. This is because router.js is not a part of the Scripts folder rather it is in the same folder as the startup.js and also the fact that it’s not defined in require.config.js.

Another difference to note is how we are setting up settings component. This is the way to setup HTML only components that have no Javascript associated with them.

The home component is registered like greeter as we had done before.

define([‘jquery’, ‘knockout’, ‘./router’, ‘bootstrap’, ‘knockout-projections’], function ($, ko, router) {
ko.components.register(‘greeter’, { require: ‘App/components/greeter/greeting’ });
ko.components.register(‘home’, { require: ‘App/pages/home/home’ });
    ko.components.register(‘settings’, {
        template: { require: ‘text!App/pages/settings/settings.html’ }
});
ko.applyBindings({ route: router.currentRoute });
});

With our components registered, we are all set to try it out.

Demo time

When we run the app, and see the Debug window, you will notice we have downloads the styles and templates that pertain to the Index page, the Home page and the greeter component. The Settings component has not been downloaded yet.

image

Now if you clear the Network activity window and click on Settings, you will note that only one file is downloaded and that is settings.html. This may seem insignificant for this demo, but has a huge impact when your applications grow big and have hundreds of components (yes, they can have 100s of components, just take my word for it Winking smile).

image

It is all the more fun to note that now if you switch back to Home page no components are called from the server because the browser has everything it needs, so unless you want to force refresh the page with data from server, navigating between pages is as fluid as a client app!

image

So we have navigation between pages and just in time loads. What about the dreaded browser Back button? Well, if you play around with it, you’ll notice back button works perfectly fine and crossroads is able to switch between views thanks to Hasher monitoring hash changes. Excellent, we could have stopped here and gone home happy but…!

Hashes in URLs, bot accessibility and best practices

If you were a observing keenly, you would have noticed that when we navigated to settings page the URL is /settings instead it is #settings. This is because we are using the age old # prefix to prevent the browser from hitting the server when someone clicks on a link. Now you realize what Hasher is doing. It’s listening to the hashchanged event and invoking crossroads (albeit in a cross browser compliant way).

This gives us a problem where our URLs are not semantic. This is a headache from bot accessibility because search robots don’t really ‘invoke’ AJAX calls to get new views when they encounter a # url. There is a nice series by Derick Bailey on drawbacks of hash URLs on Los Techies site.

As you will see from his articles, HTML5 pushState comes to the rescue to a large extent. I say large extent because once we get pushState into picture we have to start looking at the server side as well because if you don’t have # in your URL, bookmarked URLs will directly request the server to serve the URL e.g. the /settings page. In our case there is no /settings page only index.html that uses client side manipulation to get you to /settings URL. But fear not, we’ll work everything out.

Pushstate is important enough to warrant a separate article in itself. You can refer to Derick’s article for the basics, his sample is in Backbone.js and Rails. You should be able to grasp the idea, but either ways I will do it in KO and ASP.NET MVC.

Side note – Google search and Hashbangs ( #! )

Once AJAX apps became popular Google came up with a suggestion for appending a bang ( ! ) after the hash to make it apparent to search engines that the URL warranted an AJAX call, but after the initial rush to hashbang everything, the industry settled back into semantic URLs primarily because of problems associated with handling #! at the server and it’s non-standard nature.

Source Code

I have branched the master out part Part3 and it is available on Github at https://github.com/sumitkm/BuildingSpaUsingKO/tree/Part3

Tagged , , , ,

Knockout Components – Separating Templates from View Model

Part 1: Dipping your feet into Knockout JS Components

This is the second part in my Knockout JS Components series. So far we have made a simple ‘greeter’ component and used it multiple times. But our HTML template was rather simple and hard coded in the ViewModel as a string. That was fine for a small snippet but for involved templates you don’t want to stick an HTML as string. Rather you would like it to be an independent HTML that’s loaded as required.

Today we’ll see how we can separate the HTML and load it dynamically using another library called RequireJS and a plugin for it (RequireJS-Text).

If you want to follow along, you can get the source code branch for the previous article.

Quick intro to RequireJS

RequireJS is a library that is used for ‘Automatic Module Detection’ and loading of JavaScript modules and references. It was developed by James Burke from Mozilla. It is an open source project hosted on Github with a vibrant community that helps maintain it. It also has good documentation that you can refer to for getting started.

This article is not a RequireJS tutorial, instead we’ll jump right in and start using it, I’ll explain the syntax as we go along. If you have not used RequireJS before, well don’t panic, neither have I Smile.

Installing RequireJS and RequireJS-Text plugins

RequireJS has an official Nuget channel so getting the base library is easy to install via Nuget Package Manager Console, simply type in

install-package requirejs

Next we have to get the Text plugin from Github directly. You can either clone the repo from here https://github.com/requirejs/text or just download the JS file.

Once you have the file, add it to your scripts folder. I have started creating sub-folders for each library because it will come in handy later.

image

  • App/boot : This folder will contain scripts that initialize our libraries
  • App/components : This folder will contain all the components we create. Each component in turn has it’s own folder that may contain the ViewModel, HTML template and more.
  • Scripts/*: As mentioned earlier I’ve moved each library into it’s respective sub-folder under the Scripts folder. So Scripts is essentially for all libraries and frameworks that we will use (and not modify), and everything that we build will go under App.

NOTE: This folder structure is completely arbitrary. I ‘feel’ this works, you can use it, you can totally use your own structure. Just remember where your ‘root’ (folder) is Smile.

Now that we are done with the structure of the libs and sources let’s move on and configure RequireJS.

Configuring RequireJS

Under App/boot folder add a new JS file called require.configure.js. The name is, again, not a part of any convention, use what works for you, just refer it in Index.html correctly).

I have configured RequireJS initially as follows

var require = {
baseUrl: “/”,
paths: {
“bootstrap”: “Scripts/bootstrap/bootstrap”,
“jquery”: “Scripts/jquery/jquery-1.9.0”,
“knockout”: “Scripts/knockout/knockout-3.2.0beta.debug”,
“text”: “Scripts/require/text”
},
shim: {
“bootstrap”: {
deps: [“jquery”]
}
}
}

  • I’ve created a require global variable that has three properties, baseUrl, paths and shim.
  • The baseUrl property sets the root location with respect to which all other paths will be considered.
  • The paths property is assigned an object with name value pairs corresponding to the library names and their relative locations. Not the .js is stripped away from the paths.
  • The shim property provides additional dependency information. Here it shows bootstrap is dependent of jquery. The value ‘jquery’ matches the name used in ‘paths’ above.

Updating references

Now that we have configured RequireJS, technically all we need to do is load RequireJS using the configuration and all should be fine!

Well, let’s update the Index.html file to load RequireJS and remove all other Script references. We update the script references as follows:

<!–<script src=”Scripts/jquery-1.9.0.js”></script>
<script src=”Scripts/bootstrap.js”></script>
<script src=”Scripts/knockout-3.2.0beta.debug.js”></script>–>

<script src=”App/boot/require.config.js”></script>
<script src=”Scripts/require/require.js”></script>

Now you are wondering where is the greeting.js gone and how is it going to be loaded? Well there is no magic, we have a couple of more steps to go.

Add App/boot/Startup.js

In the App/boot folder add a new JavaScript file called startup.js. The name is to help us understand the process, it’s not a convention.

Add the following ‘module-definition’. You can read up about RequireJS Modules here.

define([‘jquery’, ‘knockout’, ‘bootstrap’], function ($, ko)
{
ko.components.register(‘greeter’,
{
require: ‘App/components/greeter/greeting’
});
ko.applyBindings();
});

The Startup module says that it is dependent on jQuery, KnockoutJS and BootStrap. Note, it uses the same names that were used in RequireJS configuration above. The function parameters are instances of the dependencies requested in the array, so if you put another input parameter like boots it would have instance of the bootstrap library. We’ll just keep this in mind for now.

Next it declares a function that has jQuery and KO lib references as input parameters.

In the function we ‘register’ our ‘greeter’ component. Note, that we have moved the registration from the greeting.js to startup. Also note instead of specifying the hard-coded template and view model, we are simply configuring a ‘require’ property, that points to the folder where the greeting.js is (without the js).

Well, that’s the startup configuration. Needless to say, as we add more components they will need to be registered here.

Updating our ‘greeter’ component

The first thing we do is add a greeting.html (name same as JavaScript is again not a convention, just easier to map in our heads).

It contains the same markup that we had hardcoded in the template:

image

Update greeting.js

Finally we update the greeting.js component. We comment out all the old code and replace it with the the following:

define([“knockout”, “text!./greeting.html”], function (ko, greeterTemplate) {
function greeterViewModel(params) {
var self = this;
self.greeting = ko.observable(params.name);
self.date = ko.observable(new Date());
return self;
}
return { viewModel: greeterViewModel, template: greeterTemplate };
});

So essentially we have morphed our component to a RequireJS module. Key thing to note here is use of the text plugin to load load the greeting.html. Require does all the work to load the template and stuff it into the greeterTemplate parameter.

Finally we return an object that KO accepts as definition for a module.

One more thing!

We are almost there. Those paying close attention would have noticed that we didn’t put in reference to the startup.js anywhere. How does RequireJS know how to initialize our app and it’s dependencies?

Back to the Index.html, we update the script tag that refers to RequireJS as follows:

<script data-main=”App/boot/startup” src=”Scripts/require/require.js”></script>

The data-main tag, tells Require that the main module to initialize the app is in that JS file. Thus RequireJS knows what to invoke once fully initialized.

Done!

Conclusion

If you run the application now, you’ll see the same old screen we saw in the first part. So what have we done new? Well plenty:

1. Let RequireJS load scripts dynamically.
2. Separated our KO components’ view from it’s model
3. Defined a central place to register all KO components

What we have not done is do more ‘webby’ stuff like putting in links to other possible pages of the app and creating different types of modules for each page and then showing how our app can navigate to those pages as well as load those dependencies on-demand. That’s what we’ll cover in the next part – Routing!

Source Code

The source is on Github as usual (note, after each article I am branching the code out and keeping the master for the latest updates)!

https://github.com/sumitkm/BuildingSpaUsingKO/tree/Part2

Tagged , , , ,
%d bloggers like this: