Blog Archive

Home
Filter by: KnockoutJS

This post is in our Javascript Primer series, a collections of articles aimed at .Net and back-end developers who are transition to client-side UX development.  In a previous installment, the topic of publish-subscribe design pattern was featured, and this pattern fostered loosely coupled ViewModels.  It is recommended that you read that post as well, as this edition of our primer builds on those concepts.

A basic tenant to good programming is to break down activities to small components.  Smaller functions are easier to maintain.  In many instances the information that the users are working with is best presented in logical groups, dissected so that an improper decision can never be made.  A rich user interface may force you to break a larger object into several ViewModels.  But guess what?  If you need to break information down, will also need to re-assemble this information to transmit back to mother ship to be stored in your database.

Challenges for the ViewModels

There are several challenges ahead for you if need your ViewModels to communicate, and you want to retain the agility provided to you with loose coupling.  If you recall the architecture we established with the publish and subscribe design pattern, all our “pieces” are highly independent from one another.  But we now have a complication.  Independence also means blissful ignorance.  Each ViewModel only knows how to contribute their small portions of information for glorious “mother object”.  The best it can is yield up what it has and somehow, someway, something will piece things together.

Let’s consider a code example:

We have simple project tracker that has a name, a roster of workers and a calendar that displays each workers start date.  Each tab is serviced by a ViewModel.  The “Project Info” tab shares the project name information with “Team”.  The tab “Team” shares the project team data with both the “Project Info” and the “Timeline” tabs.  This is accomplished using the publish and subscribe pattern that was detailed in this post.  You should review that post is your are unfamiliar with postaljs or with the publish and subscribe design pattern.

The challenge here is that we want a “Save” button that will easily gather the data from each tab and save it our project object.   We also want this controlling activity to be flexible and allow each ViewModel to supply the data needed without too much orchestration: in other words, we just ask the ViewModel “What do you have for a project object”, and each ViewModel fulfills its responsibility.

Pipe and Filter Pattern For Chaining Events or Commands

Many of you with a background in server side application development may recognize the pipe and filter pattern.  Simply said, it is a way to chain a set of operations that are to be performed in succession.  This diagram is a depiction of the pipe and filter:

PipesAndFilters

The “Filter” is a function that performs one thing.  Our pipe is the “orchestrator” or directory in that it will forward to each filter as ordered.

For our purposes we will continue to use postaljs as our communication mechanism.  We’ll need a pipeline that will keep track of which filter to execute and forward data to each subsequent filter of the process chain.

var pipeline = {
  index: 0,
  filters: ["edit.getViewOneData","edit.getViewTwoData","edit.finalDestination"]
 };

The property “filters” contains the names of the postaljs topics that will kick off a function.  In this case we will need 3 subscriptions that listen for items listed in the “filters” array.  Each process step, or filter, will be executed in the order that listed in the “filters” array: in this case, “edit.getViewOneData” will be executed first.  The property “index” tracks which filter is being processed.  As each filter is executed, it will increment index, then use index to access the next topic in the chain of events.  Starting off the process is accomplished in this fashion:

// Now start up the pipeline, fire off the first step that will execute the first filter
 postal.publish({
  channel: "pipenfilter",
  topic: pipeline.filters[pipeline.index],
  data: pipeline
 });

//  A sample subscription.  This will be executed first since it is listed first in the pipeline.filters array
postal.subscribe({
  channel: "pipenfilter",
  topic: "edit.getViewOneData",
  callback: function (pipeline, env) {
    fetchViewOneData(pipeline);
}
 });

//  After filter performs, it needs to call the next filter in the chain<
var fetchViewOneData = function(pipeline){
  // ... perform activities with some data

  //  To forward to next step, increment the index
  pipeline.index++;

  //  Now forward to the next filter
  postal.publish({
    channel: "pipenfilter",
    topic: pipeline.filters[pipeline.index],
    data: pipeline
  });
};

For our particular scenario with the project UX above we will have to do a few simple things:

  1. The ViewModels “ProjectInfo”, “Budget” and “Team” will need subscriptions to a “pipenfilter” channel
  2. Each ViewModel will need a corresponding filter function, so the “Team” ViewModel will get a “fetchTeamFilter”
  3. Add an endpoint in our $(document).ready section to act as a controller for the pipeline process.  Since we don’t have a controller this logic can sit here.  Naturally for cleaner production code you’ll want to be a bit cleaner and place this in a controller object.

All of the addition changes are noted with a “New pipe and filter” comment, so you can search through the Javascript to see where the changes have been made.  Most of the updates are just a few lines, and the nice thing is that the code to forward to the next filter is the same each time.  Not much exciting stuff to be seen other than incrementing the index and passing the data to the next topic.

Where No One Has Gone Before (just sayin’)

Now that you can synchronize your data, assemble it back into a proper object, you can begin your next journey.  There’s many long term benefits here that you will begin to realize.  What if you need to add an additional ViewModel, or what if you need to change which ViewModel display the groupings of data?  Without our pipe and filter solution, you would need to change a lot of things.  With what we have described here, the most that have to do is to add an additional filter name to the pipeline list and make sure that your additional ViewModel functioned properly.  The other ViewModels are left untouched.

Another benefit is also be that you can control what functions are fired while allowing the ViewModels to do their thing.  What if you had a ViewModel that published changes to other ViewModels after it finished performing calculations.  By ordering the filters in the pipeline accordingly, you can allow the ViewModels to do that hard work and be assured that all aspects of your data is up to date.  Doing more with less code means you can test and maintain this code with confidence.

This is a continuation of the Javascript Primer series where we focus on topics essential for .Net or back-end developers or who are transitioning to Javascript and client side development.  Many of the topics covered in this series will be related to producing web apps running in the browser.  Some design patterns and practices are also application to NodeJS / server-side Javascript apps as well.

Keeping IT Together

One complaint that many have when embarking on applications of medium complexity is that organizing your code is difficult; indeed, even with frameworks you can still end up with giant god object that contains all data-bindings, algorithms, helpers methods.  If you take the attitude that Javascript is a second class, toy language where you simply store jQuery animation methods and AJAX calls, you quickly end up with files that can be 3-4000 lines long!  Maintaining that is beyond torture.

A common design pattern used to alleviate this issue is the Model View ViewModel (MVVM) pattern.  The goal of MVVM is to divide up the logic of your application into UX, business logic, and data-binding activities into discrete components.  KnockoutJS is a popular framework that supports this approach.  Addy Osmani’s “Design Patterns for Javascript” defines the primary components of MVVM, and it is great primer to read if you are unfamiliar with these terms.  For our purposes:

Model will contain the data elements, such as FirstName, LastName, etc.  Essentially this is a building block for your front-end that will “model” entities such as user, customer, project, etc.

ViewModel will contain the behavior for the UI.  This can be business logic, formatting of data, and bridge the gap between data coming from a server and what is useful for the user to interactive with.  The ViewModel will also use the Models.

View will be the html document.  This will also contain the directives for what to present to the user, and will interact with the ViewModel.

We Still Have A Problem

So even with the MVVM pattern at our disposal we still have to fight bloated ViewModels.  From here out we will use a sample project for our discussion where we want to maintain project information comprised of project name, project description, and project notes, team members and a simple timeline / calendar function.  Sounds straight forward enough.  On our UI we will have a tab for grouping of information, and as information changes on a tab, we want that information available in each subsequent tab.  Again, nothing too earth shattering here.  It should look something like this JSFiddle below.  (NOTE:  For the sake of this exercise all code has been placed in the Javascript section of our JSFiddle.  You should split your code into modules so they can easily managed).

Each tab on this screen has logical groupings of information.  For the sake of argument let’s say that we decide to implement this UI with just one ViewModel for all three tabs.  For databinding we will be using KnockoutJS,  Starting out we have just one ViewModel – ProjectViewModel – that handles all updates; more specifically, we can take advantage of the data-binding facilities here, so when a team member is added, we can detect this change and automatically execute and update to the calendar.

We have three tabs – “Project Info” is pretty simple, and it uses the computed observable teamSize to display the count of the project team. You note that any changes to “Project Name” will be reflected on the “Team” tab.   The tab Team allows you to add a team member.  To support updating the calendar with the team member start date we have create subscription to the projectTeam observable array.  The tab “Timeline” has a calendar that displays the team member start date, and this is updated each time we add a new team member.  Also, any changes to the number of team members will be reflected on the first tab, “Project Info”.

Indeed this works well, since we have the advantage of one ViewModel and can benefit from easily sharing one set of data between all three tabs, But we still have an issue should we start adding more functionality and increase the properties and functions in the ProjectViewModel.  Soon maintaining the ViewModel will become difficult, and testing discrete portions of functionality will rapidly become difficult.  We need to be able to isolate or reduce the impact that the alterations made to the ViewModels have on each other.  This means adhering to the principal of “loose coupling”.

So what does it mean for us to create a ViewModel per tab?  The biggest issue now will be communicating between each ViewModel, and as always, our mantra should be “Keep it simple.  Please.  Pretty please”. So how do we achieve communicating data updates without creating three ViewModels that are still highly dependent on the others?  Our solution is to implement a subscribe and publish message architecture.  While this sounds intimidating, this simply means we will create each ViewModel with a method – a “subscription” – that will wait for a message that has the data we need.  As a corollary, each ViewModel need a way to “publish” any changes to data that occurs.

Super Simple Message with PostalJS

PostalJS is a very simple messaging framework that facilitates sub / pub messaging in a unique way.  In particular, PostalJS allows us to set up a subscription that remains “ignorant” of how the message is generated.  There is no “pre-registration processes” to map out a route between ViewModels; on the contrary, your Javascript object simply declares that will update when a subscription arrives.  This also means that several ViewModels can subscribe to an event and the publisher doesn’t care.

Here is a brief sample taken from github:

var subscription = postal.subscribe({
        channel: "orders",
        topic: "item.add",
        callback: function(data, envelope) {
            // `data` is the data published by the publisher.
            // `envelope` is a wrapper around the data & contains
            // metadata about the message like the channel, topic,
            // timestamp and any other data which might have been
            // added by the sender.
        }
    });

postal.publish({
        channel: "orders",
        topic: "item.add",
        data: {
            sku: "AZDTF4346",
            qty: 21
        }
    });

Looks pretty cool.  And simple.  So for us, our ViewModels will remain ignorant of each other, and only are aware that someone, something has sent data to it.  Another nice by product is that should one of the ViewModels fail, the impact is greatly reduced.  So should the ViewModel with the calendar fail, the other tabs could still collect data and function.  Better yet, adding new features to a ViewModel is going to be easier to achieve since we can test in isolation, and if the new features do not interrupt our sub / pub messaging, we can feel confident that new changes can be rolled into production without bringing down the entire application. Let’s look at the results, then examine the changes to our app’s architecture.

A Brave New World

If you open the Javascript tab of the JSFiddle, you’ll see that we have broken up the ProjectViewModel into 3 ViewModels:  TeamViewModel, TimelineViewModel, and of course the remants of ProjectViewModel.  We’ll take the updates on at time, focusing on the feature in the UI and work back to the code.

Project Name As before, entering the project name in the “Project Info” tab updates the title in the “Team” tab.  Same as before, the update happens when the input box loses focus.  Now let’s focus on the code.  Open up the Javascript in the JSFiddle, and you’ll see some drastic changes.  In the ProjectViewModel we have created a Knockout trigger that publishes a message:

</pre>
<pre data-language="js">_projectName.subscribe(function(newValue){

        //    Now use PostalJS to push message out
        postal.publish({
            channel: "project",
            topic: "edit.projectNameChange",
            data: {
                projectName: _projectName()
            }
        });
    });

So what we are doing here telling Knockout “Anytime there is a change to the observable _projectName, fire off a function that publishes a piece of data with the new value of _projectName”.  That’s it.  ProjectViewModel has fulfilled its responsibility and told anyone who will listen that a change has taken place.  Now find the TeamViewModel object.  Here we have a subscription that waits for a message containing _projectName updates:

</pre>
<pre data-language="js">var projectNameChangeSubscription = postal.subscribe({
        channel: "project",
        topic: "edit.projectNameChange",
        callback: function(data, envelope) {
            _projectName(data.projectName);
        }
    });

We get the data, and merely update an observable on the TeamViewModel.  It should be apparent by now that neither ProjectViewModel nor TeamViewModel “know” about each.  ProjectViewModel says “_projectName update ready” and who can handle it, does so. TeamViewModel just grabs the update, uses it.  That’s it.  The messaging works by creating a “channel” – in this case “project” – further defines the message with a topic – “edit.projectNameChange”.  This means you can a single channel that support multiple topics and narrowly define your event messages.

ProjectTeam Update Play around with the “Team” tab and add some team members with different dates.  The operates just as before.  Under the hood, the code in TeamViewModel that handles the publishing is:

</pre>
<pre data-language="js">_projectTeam.subscribe(function(){
        //    this is how postaljs publishes events
        postal.publish({
            channel: "project",
            topic: "edit.teamUpdate",
            data: {
                projectTeam: ko.toJS(_projectTeam)
            }
        });

    });

As before, we are asking KnockoutJS to watch for changes to the _projectTeam array, and when a change occurs, we publish a different message.  The portion of code – topic: “edit.teamUpdate” distinguishes this event from the previous on.  We simply take our observableArray and convert it a plain Javascript script array and throw out to whoever wants it.  If you look in both ProjectViewModel and TimelineViewModel you’ll see subscriptions that handle this topic.  This brings us to another important aspect of messaging and postaljs’ strength:  should we want to add more ViewModels that need _projectTeam updates, we only need to subscribe to the topic “edit.teamUpdate”.  We could subscribe 50 more times if we wanted.  The publisher / source ViewModel does not need any alteration, and this achieves our goal of loose coupling.

What Are The Other Benefits?


Looking at our ViewModels, you may have noticed that we are exposing less in the return statements, and with each ViewModel handling less functionality they become simpler to read and maintain.  Imagine that the needed to support 20 different data entry input boxes – one monster ViewModel would have a huge return statement.  It makes it hard to keep things straight in one “god” class.

With PostalJS and event messaging we no longer need to expose an entry point in our objects for data to be passed.  The subscriptions allow the ViewModel to handle receiving update messages internally.  A quite common scenario would be responding to an AJAX update.  With PostalJS you can avoid calls to each ViewModel when new data arrives from the server.  Simply publish to the appropriate topic and let the ViewModels respond as they need.

“This. Is Not. For. Practice!” – a phrase used to emphasize that you must get things right.  Mentors have used it to mean “Get serious, now!”.

For years jQuery has been a tremendous productivity boost for client-side development; so successful, that it gave rise the Single Page Application (SPA) where a good portion of your application logic was now written with Javascript. Soon, so soon, we all learned that the increased complexity of our client side solutions required good organization, a better architecture.  Time to get serious about clean code.

If you are .Net developer, then many times you can fall into the ECMAScript trap: all ECMAScript must be the same.  What I know from C# must be applicable to Javascript, ’cause it looks the same. Sad news, it’s not. Javascript executes in a much different environment. And to make things more confusing, close cognates such as this are not close enough. “this” in C# is a reference to the current object. “this” is Javascript is , well, it all depends. “this” in Javascript changes context dependent on many factors.  A good reference is here at Mozilla.  Let’s create a quick summary, and where relevant we’ll talk relevant areas that impact programming practice:

Global Context

When you are outside any function, this is referred to as the global context.  ”this” will refer to document.  So if you fire up the console and perform this test:


console.log(this == document); // true.

And in web browsers this also equals the window.  So:


console.log(this == window); // true.

Yikes!  Wait there’s more.  Try this little piece:


var yikes = "ouch";

console.log(window.yikes); // ouch

window is our global memory space.  So think back to any client side code you have written, and this should be very familiar to you:


<script type="text/javascript" src="scripts/jquery.min.js"></script>

This loads jQuery into the global memory space.   Go look at window and you will see “window.$” and “window.jQuery”.  You guessed it, jQuery is now loaded into the global namespace.

This may seem like a digression, but we need to pause at this very important point.  You must be really careful what you put into this global space.  As you grow in Javascript capability you will eventually develop your own utils or libraries.  So consider this very innocent utility file:

  function objectToArray(sourceObj) {
    var results = [];

    for (var key in sourceObj) {
      if (sourceObj.hasOwnProperty(key)) {
        var newObj = sourceObj[key];
        newObj.objectKey = key;
        results.push(newObj);
      }
    }

    return results;
  };

function localize(t) {
  var d = new Date(t + " UTC");
  return d;
}

function parseDecimal(d, zeros, trunc) {
  if (d == null)
    return 0;

  if (typeof d == "number") {
    return parseFloat(d);
  }

  d = d.replace(/[a-zA-Z\!\@\#\$\%\^\&\*\(\)\_\+\-\=\{\}\|\[\]\\\:\"\;'\<\>\?\,\/\~\`]/g, "");
  while (d.indexOf(".") != d.lastIndexOf("."))
  d = d.replace(/\./, "");

  if (typeof zeros == 'undefined' || zeros == "") {
    return parseFloat(d);
  }
  else {
    var mult = Math.pow(10, zeros);
    if (typeof trunc == 'undefined' || (trunc) == false)
      return parseFloat(Math.round(d * mult) / mult);
    else
      return parseFloat(Math.floor(d * mult) / mult);
    }
};

All of these functions are now attached to the global namespace, our what is called “polluting the global namespace”.  Most likely a utility class will have 20 – 30 functions, not the mere three listed above.  These functions will remain in memory until the user refreshes or navigates away from the page.  With a small app, this will be no problem, but anything with a moderate degree of code will soon balloon and consume memory.  And in some cases, such as a mobile friendly websites, you want to conserve as much memory as you can, only loading the objects that you need then allowing them to be garbage collected.

Wow – we’ve only covered “this” in a global context, and if your head isn’t a little numb, don’t worry, do another shot and see if it gets worse!

Function Context – Simple Call

Here we get a strange, as this is the rule:  ”this” will depend on how the function is called.  Consider this code:


var myFunc = function(){
   return this;
 };

myFunc() == window;

Since we are not using strict mode “this” must refer to something so it will default to the global object.  Changing the code to:


var myFunc = function(){
  "use strict";
  return this;
 };

myFunc() == "undefined";

Function Context – As An Object Method

The rule here is “this” refers to the object that the method is called on.  For example:


var mathDoer = {
  someNumber: 13,

  addSomeNumber: function(addMe){
    return this.someNumber + addMe;
  };
 };

mathDoer.addSomeNumber(7); // returns 20

You’ll note that both mathDoer.someNumber and mathDoer.addSomeNumber() are public in scope.  When first developing in Javascript it may be tempting to create your objects as depicted below, and while it is legitimate, it will lead to clutter very quickly:


var mathDoer = {};

mathDoer.someNumber = 13;

mathDoer.someArray = [];

mathDoer.addSomeNumber = function(){ ...};

Imagine this is a none trivial object, and you will have a cluttered mess.  Also, all your methods and properties are public, which you may not want to expose.

Function Context – As A Constructor

When used in a constructor “this” will refer to the object that is being instantiated.  This is best illustrated with the following:


var mathDoer = function(){
this.someNumber = 13;

this.addSomeNumber = function(addMe){
    return this.someNumber + addMe;
  };
 };

var mathIsFunObj = new mathDoer();

mathIsFunObj.addSomeNumber(7); // returns 13

Many of you may be coming to Javascript via KnockoutJS, a data binding library that provides two way binding between the DOM and Javascript objects.  Many of the KnockoutJS samples use this “style” for creating ViewModels:


var mathDoerViewModel = function(){
  this.justAnInt = 5;
  this.someNumber = ko.observable();

  this.addSomeNumber = function(addMe){
    return addMe + this.someNumber();
  };
};

var vm = new mathDoerViewModel();
ko.applyBindings(vm);

Again, our observables and functions are public in scope.  If you have a separate file for this ViewModel and simply include it with the HTML your “vm” variable is now added to the window object and part of the global memory space.  This can be considered good or bad.  From a diagnostics perspective, you can sit at the console and see what our ViewModel is doing by simply issuing commands like “vm.someNumber(45);”  Good for debugging.  This is also considered bad by others for two reasons: everything is public, and this can lead to bloated objects that are hard to use; and, you have added yet another item to the global memory space.  Imagine you have several ViewModels for a single page.  Things can get confusing very quickly.

So how can you make items private?  Remember that the scope of “this” when used in a constructor is a reference to that object – in our case that object is mathDoerViewModel.  If you were merely to declare a variable in the constructor, the scope of that variable would be local to the constructor.  This “hides” the variable from contexts that are outside the scope of the constructor.  That would look like this:


var mathDoerViewModel = function(){
  var _justAnInt = 5; //this makes the variable private

  //  function is local in scope
  var privateFunction = function(){

    //  our locals are available as well a methods and properties from the object ("this")
    return _justAnInt + this.someNumber();
  };

  this.someNumber = ko.observable();

  this.addSomeNumber = function(addMe){
    return addMe + this.someNumber();
  };
};

From the console still can interact with mathDoerViewModel.someNumber() and mathDoerViewModel.addSomeNumber(). We also have private functions and variables now: _justAnInt and privateFunction. For the .Net developer these conventions should have more familiar feel.

When you scour the web for Javascript code, you’ll find that many of the Javascript heavies will use a different standard for variable / scope hiding. We touch on that briefly here before we move on.  In Javascript, your constructor returns a reference to the object you are creating.  In other words, your constructor will return a version of “this” that refers to the objects properties and functions.  However, your constructor can also return an object.  This gives you great flexibility, and makes the  “Module Reveal Pattern” possible.  First here is what our ViewModel would look like using the Module Reveal Pattern:


var mathDoerViewModel = function(ko){

  var _justAnInt = 0;
  var _someNumber = ko.observable();

  var privateFunction = function(){
    return _justAnInt + _someNumber();
  };

  var addSomeNumber = function(addMe){
    return addMe + _someNumber();
  };

  var setJustAnInt = function(value){
    _justAnInt = value;
  };

  var showMeTheInt = function(){
    return justAnInt;
  };

  //  We return an object that refers to items we want to be public
  return {
    someNumber: _someNumber,
    addSomeNumber: addSomeNumber,
    showMeTheInt: showMeTheInt
  };
};

Looks a little different. In our constructor we are creating local variables and local functions, and in fact our observable – _someNumber – is now a local variable. But we “reveal” the items that we want to be public with the “return” statement. So in this case, we return an object with someNumber that references _someNumber, and references addSomeNumber. As a result, we can create:

  var vm = new mathDoerViewModel(ko);

  // Set value of someNumber
  vm.someNumber(35);
  vm.addSomeNumber(5); // returns 40

  //  Let's use our setter
  vm.setJustAnInt(12);
  vm.showMeTheInt(); // returns 12

Notice that we are passing in a “ko” variable in the constructor call. This serves many purposes: firstly, it makes the ViewModel modular, and allows us to load the module asynchronously with AMD tools like requirejs or curljs; secondly, the constructor signature lets us know that we are depending “ko” to make our ViewModel work; finally, it gives us a tiny speed boost as now that “ko” is local, since Javascript does not have to search up the stack to find it.

You should avail yourself of the fantastic book “Learning Javascript Design Practises” by Addy Osmani.  He’s been kind enough to place a copy online.  This will help you understand some of the code that is that would otherwise seem very strange compared to what you are used to in C#.

Function Context – As A DOM Handler

Moving on the DOM, “this” takes on a different context.  You’ll most likely be familiar with this common jquery statement:


$(".apparea").on("mouseover", ".milestone-border", function (event) {
//   here this means the DOM element with a class of "milestone-border"

$(this).addClass("selected-children");
 });

The rule here is that “this” means the DOM object that fires the handler.  So in this case “this” is equal to event.currentTarget.

Go Forth And Create

ImageBy now your head should hurt a little, with all these nuances it’s wonder that you don’t feel more beaten up.  That’s where the complexity of web development is under appreciated.  Hopefully we have covered enough here for you to save some time debugging, designing, or trying to understand some the vast Javascript frameworks, utils and libraries that are out there.  If you are coming from .Net and are new to Javascript, you avoid the trap that many have fallen into of creating monstrous Javascript objects of pure public functions and properties jammed into a single file.  This will lead to a deep valley of frustration when it comes time to refactor your code after you realize you have a hard time maintaining things.  If you can keep your code modular and have things reside in separate files, you’ll be better off.

We covered “this” in order to reveal some deeper yet vital nuances to Javascript.  Mastering “this” and the related topics above are going to help.  A lot.  This brings Javascript from being a “toy” to  really productive platform because you can avoid some pitfalls that slow you down.  In future posts we continue to build on this foundation where we focus on modular design and asynchronous loading.

ImageOn the quest to provide a rich user interface experience on his current project, Sensei has been experimenting with KnockoutJS by Steve Sanderson.  If you haven’t reviewed it’s capabilities yet  it would be well worth your while.  Not only has Steve put together a great series of tutorials, but he has been dog fooding it with Knockout.  The entire documentation and tutorial set is completed used Knockout.  Another fine source is Knockmeout.net by Ryan Niemeyer.  Ryan is extremely active on StackOverflow answering questions regarding Knockout, and also has a fine blog that offers very important insight on developing with this framework.

KnockoutJS is a great way to re-organize your client side code.  The goal of  this post is not to teach you KnocoutJS; rather, Sensei wants to point out other benefits – and a few pitfalls – to adopting its use.  In years past, it’s been difficult to avoid writing spaghetti code in Javascript.  Knockout forces you to adopt a new pattern of thought for organizing your UI implementation.  The result is a more maintainable code base.  In the past you may have written code similar to what Sensei use to write.  Take for example assigning a click event to a button or href in order to remove a record from a table:

&lt;table&gt;
  &lt;thead&gt;&lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;a onclick=&quot;deleteRecord(1); return false;&quot; href=&quot;#&quot;&gt;Customer One&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;1313 Galaxy Way&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;a onclick=&quot;deleteRecord(2); return false;&quot; href=&quot;#&quot;&gt;Customer Two&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;27 Mockingbird Lane&lt;/td&gt;
    &lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
function deleteRecord(id){
  //  Do some delete activities ...
}
&lt;/script&gt;

You might even went as far as to assign the onclick event like so:

$(document).ready(function(){
  $(&quot;tr a&quot;).on('click', function(){
    //  find the customer id and call the delete record
  });
});

The proposition offered by Knockout is much different.  Many others much more conversant in design patterns and development than Sensei can offer better technical reasons why you sound use Knockout.  Sensei likes the fact that it makes thinking about your code much simpler.  As in:

 
<td><a data-bind="click: deleteRecord($data)" href="#">Customer One</a></td>

Yep, you have code mixed in with your mark up, but so what.  You can hunt down what’s going on, switch to your external js file to review what deleteRecord is supposed to do.  It’s as simple as that.  Speaking of js files, Knockout forces you to have a more disciplined approach organizing your javascript.  Here is what the supporting javascript could look like:

var CustomerRecord = function(id, name){
  //  The items you want to appear in UI are wrapped with ko.observable
  this.id = ko.observable(id);
  this.name = ko.observable(name);
}

var ViewModel = function(){
var self = this;
  //  For our demo let's create two customer records.  Normally you'll get Json from the server
  self.customers = ko.observableArray([
    new CustomerRecord(1, &quot;Vandelay Industries&quot;),
    new CustomerRecord(2, &quot;Wiley Acme Associates&quot;)
  ]);

  self.deleteRecord = function(data){
    //  Simply remove the item that matches data from the array
    self.customers.remove(data);
  }
}

var vm = new ViewModel();
ko.applyBindings(vm);

That’s it.  Include this file with your markup and that’s all you have to do.  The html will change too.   Knockout will allow you to produce our table by employing the following syntax:

<tbody data-bind=”foreach: customers”>
<tr>
<td><a href=”#” data-bind=”click:  deleteRecord($data)”><span data-bind=”text: id”></span></a></td>
<td><span data-bind=’text: name”></span></td>
<tr>
</tbody>

These Aren’t the Voids You’re Looking For

So we’re all touchy feely because we have organization to our Javascript and that’s a good thing.  Here’s some distressing news – while Knockout is a great framework, getting the hang of it can be really hard.  Part of the reason is Javascript itself.  Because it’s a scripting language, you end up with strange scenarios where you have a property that appear to have the same name but different values.  You see, one of the first rules of using Knockout is that observables ARE METHODS.  You have to access them with (), as in customer.name(), and not customer.name.  In other words, in order for you to assign values to an observable you must:


customer.name(&quot;Vandelay Industries&quot;);

//  Don't do this - you create another property!!

customer.name = &quot;Vandelay Industries&quot;;

What? Actually, as you probably have surmised, you get .name() and .name, and this causes great confusion when you are debugging your application in Firebug.  Imagine you can see that customer.name has a value when you hit a breakpoint, but its not what you’re looking for.  Sensei developed a tactic to help verify that he’s not insane, and it works simply.  When in doubt, go the console in Firebug and access your observable via the ViewModel; so in our case you could issue:

vm.customer.name();

When name() doesn’t match your expectation you’ve most likely added a property with a typo.  Check with

vm.customer.name;

It sounds silly, but you can easily spend a half hour insisting that you’re doing the right thing, but you really confusing a property with a method.  Furthermore, observable arrays can also be a source of frustration:

// This is not the length of the observable array. It will always be zero!!!
vm.customers.length == 0;

// You get the length with this syntax
vm.customers().length;

Knock ‘em inta tamarra, Rocky

Had Sensei known the two tips before starting he would have save a lot of time.  There are many others, and they are best described by Ryan Niemeyer in his post 10 things to know about Knockout from day one.  Read this post slowly.  It will save you a lot of headache.  You may familiar with jQuery and Javascript, but Knockout introduces subtle differences that will catch you off guard.  That’s not a bad thing, it’s just different than what you may be used to.  Ryan also makes great use of JS Fiddle and answers most of his StackOverflow questions by using examples.  Those examples are in many cases easier to learn from than the tutorial since the scope is narrower than the instruction that Steve Sanderson gives.  It really allows you play along as you learn.

ImageOn the quest to provide a rich user interface experience on his current project, Sensei has been experimenting with KnockoutJS by Steve Sanderson.  If you haven’t reviewed it’s capabilities yet  it would be well worth your while.  Not only has Steve put together a great series of tutorials, but he has been dog fooding it with Knockout.  The entire documentation and tutorial set is completed used Knockout.  Another fine source is Knockmeout.net by Ryan Niemeyer.  Ryan is extremely active on StackOverflow answering questions regarding Knockout, and also has a fine blog that offers very important insight on developing with this framework.

KnockoutJS is a great way to re-organize your client side code.  The goal of  this post is not to teach you KnocoutJS; rather, Sensei wants to point out other benefits – and a few pitfalls – to adopting its use.  In years past, it’s been difficult to avoid writing spaghetti code in Javascript.  Knockout forces you to adopt a new pattern of thought for organizing your UI implementation.  The result is a more maintainable code base.  In the past you may have written code similar to what Sensei use to write.  Take for example assigning a click event to a button or href in order to remove a record from a table:

&lt;table&gt;
  &lt;thead&gt;&lt;/thead&gt;
  &lt;tbody&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;a onclick=&quot;deleteRecord(1); return false;&quot; href=&quot;#&quot;&gt;Customer One&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;1313 Galaxy Way&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr&gt;
      &lt;td&gt;&lt;a onclick=&quot;deleteRecord(2); return false;&quot; href=&quot;#&quot;&gt;Customer Two&lt;/a&gt;&lt;/td&gt;
      &lt;td&gt;27 Mockingbird Lane&lt;/td&gt;
    &lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;

&lt;script type=&quot;text/javascript&quot;&gt;
function deleteRecord(id){
  //  Do some delete activities ...
}
&lt;/script&gt;

You might even went as far as to assign the onclick event like so:

$(document).ready(function(){
  $(&quot;tr a&quot;).on('click', function(){
    //  find the customer id and call the delete record
  });
});

The proposition offered by Knockout is much different.  Many others much more conversant in design patterns and development than Sensei can offer better technical reasons why you sound use Knockout.  Sensei likes the fact that it makes thinking about your code much simpler.  As in:

 
<td><a data-bind="click: deleteRecord($data)" href="#">Customer One</a></td>

Yep, you have code mixed in with your mark up, but so what.  You can hunt down what’s going on, switch to your external js file to review what deleteRecord is supposed to do.  It’s as simple as that.  Speaking of js files, Knockout forces you to have a more disciplined approach organizing your javascript.  Here is what the supporting javascript could look like:

var CustomerRecord = function(id, name){
  //  The items you want to appear in UI are wrapped with ko.observable
  this.id = ko.observable(id);
  this.name = ko.observable(name);
}

var ViewModel = function(){
var self = this;
  //  For our demo let's create two customer records.  Normally you'll get Json from the server
  self.customers = ko.observableArray([
    new CustomerRecord(1, &quot;Vandelay Industries&quot;),
    new CustomerRecord(2, &quot;Wiley Acme Associates&quot;)
  ]);

  self.deleteRecord = function(data){
    //  Simply remove the item that matches data from the array
    self.customers.remove(data);
  }
}

var vm = new ViewModel();
ko.applyBindings(vm);

That’s it.  Include this file with your markup and that’s all you have to do.  The html will change too.   Knockout will allow you to produce our table by employing the following syntax:

<tbody data-bind=”foreach: customers”>
<tr>
<td><a href=”#” data-bind=”click:  deleteRecord($data)”><span data-bind=”text: id”></span></a></td>
<td><span data-bind=’text: name”></span></td>
<tr>
</tbody>

These Aren’t the Voids You’re Looking For

So we’re all touchy feely because we have organization to our Javascript and that’s a good thing.  Here’s some distressing news – while Knockout is a great framework, getting the hang of it can be really hard.  Part of the reason is Javascript itself.  Because it’s a scripting language, you end up with strange scenarios where you have a property that appear to have the same name but different values.  You see, one of the first rules of using Knockout is that observables ARE METHODS.  You have to access them with (), as in customer.name(), and not customer.name.  In other words, in order for you to assign values to an observable you must:


customer.name(&quot;Vandelay Industries&quot;);

//  Don't do this - you create another property!!

customer.name = &quot;Vandelay Industries&quot;;

What? Actually, as you probably have surmised, you get .name() and .name, and this causes great confusion when you are debugging your application in Firebug.  Imagine you can see that customer.name has a value when you hit a breakpoint, but its not what you’re looking for.  Sensei developed a tactic to help verify that he’s not insane, and it works simply.  When in doubt, go the console in Firebug and access your observable via the ViewModel; so in our case you could issue:

vm.customer.name();

When name() doesn’t match your expectation you’ve most likely added a property with a typo.  Check with

vm.customer.name;

It sounds silly, but you can easily spend a half hour insisting that you’re doing the right thing, but you really confusing a property with a method.  Furthermore, observable arrays can also be a source of frustration:

// This is not the length of the observable array. It will always be zero!!!
vm.customers.length == 0;

// You get the length with this syntax
vm.customers().length;

Knock ‘em inta tamarra, Rocky

Had Sensei known the two tips before starting he would have save a lot of time.  There are many others, and they are best described by Ryan Niemeyer in his post 10 things to know about Knockout from day one.  Read this post slowly.  It will save you a lot of headache.  You may familiar with jQuery and Javascript, but Knockout introduces subtle differences that will catch you off guard.  That’s not a bad thing, it’s just different than what you may be used to.  Ryan also makes great use of JS Fiddle and answers most of his StackOverflow questions by using examples.  Those examples are in many cases easier to learn from than the tutorial since the scope is narrower than the instruction that Steve Sanderson gives.  It really allows you play along as you learn.


ActiveEngine Software by ActiveEngine, LLC.