Just Enough To Be Dangerous

This is my brain on web development.

ThatConference Session List 2: Knockout My Bootstrap!

| Comments

1
2
3
4
# REMEMBER: follow along with these examples by cloning the
#   repository and checking out the tag for each step
$ git clone https://github.com/mheggeseth/ThatSessions.git
$ git checkout -f [tag-name-for-step]

Last time, we used jQuery, JSONP, and OData to load a list of conference sessions into some HTML Bootstrap boilerplate. We got loading to work, but our page isn’t very pretty or useful yet so we’re going to fix that (at least part way).

Enter KnockoutJS

git checkout -f knockoutjs

Obviously, we’ll add the KnockoutJS library.

1
<script type="text/javascript" src="js/knockout-2.3.0.js"></script>

Next, we’ll make a few simple changes to our JavaScript.

1
2
3
4
5
6
7
8
9
10
11
var viewModel = {
    sessions: ko.observableArray()
};

$.ajax({
    url: "http://www.thatconference.com/odata/api.svc/Sessions?$format=json&$callback=?",
    dataType: "jsonp",
    success: function (data) {
        viewModel.sessions(data.d);
    }
});

First, we defined a viewModel object containing a single observableArray to be a container for our sessions. Then we set the sessions observable to the array of sessions returned by the AJAX request.

Notice that our JavaScript has now lost any notion of HTML or the DOM. This is a good thing. A nice benefit of using Knockout’s MVVM pattern is separating your data (the view model) from how the data is presented in HTML markup (the view). This allows the HTML to accurately describe, to a great extent, the behavior of the page. This is a distinct advantage over jQuery, whose behavior is generally defined in JavaScript and you are left to guess what role markup elements play based on context clues in their IDs or CSS class names.

Let’s update our HTML using Knockout’s data-bind attribute to bind our session list to the page.

1
2
3
4
5
6
<div class="container">
    <span data-bind="visible: !sessions().length">Loading sessions...</span>
    <ul class="list-unstyled" data-bind="foreach: sessions">
        <li data-bind="text: Title"></li>
    </ul>
</div>

The foreach: sessions binding tells Knockout to repeat the element’s inner HTML for each object in the sessions array. The binding context of the inner HTML of <ul data-bind="foreach: sessions"> then becomes the current element of sessions. So <li data-bind="text: Title"></li> will add a list item for each session whose value is the Title property of the session.

Notice that we added another element in there: <span data-bind="visible: !sessions().length">Loading sessions...</span>. Knockout’s visible binding shows the current element if its value is truthy and hides it when its value is falsey. This allows us to easily provide a friendly loading message before sessions are loaded and then take it away once we’ve loaded at least one session.

We forgot to do one thing, probably the most important thing. We need to tell Knockout to apply the bindings in the HTML to a view model. We add a call to ko.applyBindings to the end of our JavaScript after we’ve defined our view model. Without this, the data-bind attributes we added to the markup are about as useless as a white crayon.

1
2
//find KO binding declarations and associate them with target viewModel members
ko.applyBindings(viewModel);

So this is all fine and good, but you’ve probably noticed that with the exception of the loading indicator, we haven’t changed the look and feel of our page at all. However, the addition of Knockout to manage data and its application to the DOM should pay big dividends in the future. For one, because sessions is not just any array but an observable array, if we added or removed a session, Knockout would automatically update the view: a task that would have required significantly more code with our previous jQuery setup.

For reference, here’s the diff for our latest set of changes to index.html.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
 <div class="container">
-        <ul id="sessionList" class="list-unstyled"></ul>
+        <span data-bind="visible: !sessions().length">Loading sessions...</span>
+        <ul class="list-unstyled" data-bind="foreach: sessions">
+            <li data-bind="text: Title"></li>
+        </ul>
 </div>

 <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
+    <script type="text/javascript" src="js/knockout-2.3.0.js"></script>
 <script type="text/javascript" src="js/bootstrap.min.js"></script>
 <script type="text/javascript">
+        var viewModel = {
+            sessions: ko.observableArray()
+        };
+
     $.ajax({
         url: "http://www.thatconference.com/odata/api.svc/Sessions?$format=json&$callback=?",
         dataType: "jsonp",
         success: function (data) {
-                var sessions = data.d;
-                var $sessionList = $("#sessionList");
-                $.each(sessions, function(index, session) {
-                    $("<li></li>").text(session.Title).appendTo($sessionList);
-                });
+                viewModel.sessions(data.d);
         }
     });
+
+        //find KO binding declarations and associate them with target viewModel members
+        ko.applyBindings(viewModel);
 </script>
   </body>

Bootstrap Window Dressing

git checkout -f bootstrap-style

So now that we have the beginnings of an application, let’s use Bootstrap to make it look a little bit nicer. First, we’ll give the navigation bar fixed layout so that it stays at the top of the screen as we scroll. This is as easy as adding the navbar-fixed-top style to the navbar tag. Bootstrap requires us to add 70px of padding to the top of the body tag to facilitate the fixed navbar behavior so we’ll do that too.

1
2
3
4
5
6
7
8
9
10
11
<head>
...
    <style type="text/css">
        body { padding-top: 70px; }
    </style>
</head>
<body>
    ...
    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">...</nav>
    ...
</body>

Now, let’s add some style to our list. First, we’ll give our loading indicator a little flare by adding the alert style (in a non-threatening way).

1
<div class="alert alert-info" data-bind="visible: !sessions().length">Loading sessions...</div>

Then we’ll turn our list into a list group and use labels to highlight some useful information about the session like scheduled time (with a little help from Moment.js), location, category, and level.

1
2
3
4
5
6
7
<ul class="list-group" data-bind="foreach: sessions">
    <li class="list-group-item">
        <span class="label label-primary" data-bind="text: new moment(ScheduledDateTime).format('ddd M/D/YY h:mm a') + ' | ' + ScheduledRoom"></span>
        <span class="label label-default" data-bind="text: Category + ' | ' + Level"></span>
        <h4 class="list-group-item-heading" style="margin-top:5px" data-bind="text: Title"></h4>
    </li>
</ul>

Here are all the changes we just made:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
@@ -4,13 +4,15 @@
     <title>That Conference / Sessions</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <!-- Bootstrap -->
-    <!-- <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css"> -->
     <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
-    <!-- <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css"> -->
     <link rel="stylesheet" type="text/css" href="css/bootstrap-theme.min.css">
+    <style type="text/css">
+        /* Necessary for fixed header http://getbootstrap.com/components/#navbar-fixed-top */
+        body { padding-top: 70px; }
+    </style>
   </head>
   <body>
-    <nav class="navbar navbar-inverse" role="navigation">
+    <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
         <div class="navbar-header">
             <a class="navbar-brand visible-xs" href="#">That / Sessions</a>
             <a class="navbar-brand hidden-xs" href="#">That Conference / Sessions</a>
@@ -18,17 +20,20 @@
     </nav>

     <div class="container">
-        <span data-bind="visible: !sessions().length">Loading sessions...</span>
-        <ul class="list-unstyled" data-bind="foreach: sessions">
-            <li data-bind="text: Title"></li>
+        <div class="alert alert-info" data-bind="visible: !sessions().length">Loading sessions...</div>
+        <ul class="list-group" data-bind="foreach: sessions">
+            <li class="list-group-item">
+                <span class="label label-primary" data-bind="text: new moment(ScheduledDateTime).format('ddd M/D/YY h:mm a') + ' | ' + ScheduledRoom"></span>
+                <span class="label label-default" data-bind="text: Category + ' | ' + Level"></span>
+                <h4 class="list-group-item-heading" style="margin-top:5px" data-bind="text: Title"></h4>
+            </li>
         </ul>
     </div>

-    <!--<script src="//code.jquery.com/jquery.js"></script>-->
     <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
     <script type="text/javascript" src="js/knockout-2.3.0.js"></script>
-    <!--<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>-->
     <script type="text/javascript" src="js/bootstrap.min.js"></script>
+    <script type="text/javascript" src="js/moment.min.js"></script>
     <script type="text/javascript">
         var viewModel = {
             sessions: ko.observableArray()

Next Time: Making it Useful

So now that we have a session list that’s marginally pretty and functional, we should probably make it useful too. Next time, we’ll organize the sessions in a relevant way and make it easy to track favorites.

A Simple, Responsive Conference Session List: Part 1

| Comments

August 2012 was the inaugural That Conference. It was an awesome conference (one that I will attend as long as it keeps going), but having just my iPhone with me, it was a challenge to peruse upcoming sessions using the conference’s less-than-mobile-friendly website. So before I geared up to attend That Conference 2013, I built a mobile-friendly page for browsing sessions.

What I wanted

  • View sessions as simply as possible. Minimize cruft.
  • Hide or diminish irrelevant information. Specifically, hide sessions that have already happened.
  • Track favorite sessions without accounts.
  • Tolerate inconsistent connectivity and bandwidth (it’s a conference, after all).
  • Provide a usable, consistent experience at any screen width.

To be clear, the That Conference organizers did a great job creating a mobile app for 2013 (which I didn’t know about when I wrote my page). I tried it and liked it, but there were a couple features my page had that were important to me so I ended up using my page for most of the conference. I’m looking forward to seeing how the mobile app improves for 2014. It will probably have useful features that I haven’t even thought of.

Part 1 of N…

To keep this post from becoming The Odyssey, I’m breaking down the construction and evolution of the page into a series of posts. I’m not sure how many there will be yet. My intention is to go step-by-step through my “process” of building the page, paying special attention to the tools and techniques I used along the way as well as well as pointing out difficulties and areas for improvement. Let’s get started!

Want to follow along? Install Git, clone the repo below, then checkout the specified tag to get the full code state for that step.

git clone https://github.com/mheggeseth/ThatSessions.git

Bootstrap boilerplate

git checkout -f bootstrap-boilerplate

We’ll start with the HTML boilerplate provided by Bootstrap. If you aren’t famliar with Bootstrap, you’re at least familiar with its style (Twitter, Angular, and the web sites for many other open source frameworks). As a nice-looking, easy-to-use, responsive-by-default front-end library, it’s an easy win for small projects.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html>
  <head>
    <title>That Conference / Sessions</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- Bootstrap -->
    <link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
  </head>
  <body>
    <nav class="navbar navbar-inverse" role="navigation">
        <div class="navbar-header">
            <a class="navbar-brand visible-xs" href="#">That / Sessions</a>
            <a class="navbar-brand hidden-xs" href="#">That Conference / Sessions</a>
        </div>
    </nav>

    <div class="container">
        <div class="jumbotron">
            <div class="container">
                <h1>Hello, world!</h1>
                <p>Do you think we should write some code to load the sessions? Yes.</p>
            </div>
        </div>
    </div>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="//code.jquery.com/jquery.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
  </body>
</html>

I’ve already made one nice customization to the boilerplate, taking advantage of the responsive utility classes that come with Bootstrap. When the browser width is narrow (i.e. mobile devices) shorten the header title to save space. The visible-xs class ensures an element will only be visible when the browser width is “extra small”. hidden-xs ensures an element is always hidden when the browser width is narrow.

1
2
3
4
...
<a class="navbar-brand visible-xs" href="#">That / Sessions</a>
<a class="navbar-brand hidden-xs" href="#">That Conference / Sessions</a>
...

This will come in handy later in case we want to add other controls to the page header and keep them tidy on mobile devices.

Tangent: Ad-Hoc HTTP Server with Node and http-server

If you have a favorite way of spinning up ad-hoc local HTTP servers, vaya con dios. For me, I turn to the http-server package for Node. Install it globally and you can fire up an HTTP server from any location with http-server. It even gives you a unique port if you spin up multiple servers. Not too bad.

Get me some sessions (with help from OData, jQuery, & JSONP)

git checkout -f load-sessions

So we have a fairly nice-looking page that does exactly nothing. Let’s get some sessions.

First I have to figure out how to do that. I’m somewhat familiar with OData so that’s what I’ll sniff out first. If you aren’t familiar, OData is short-hand for the Open Data Protocol: an effort to document and encourage a standard for data APIs on the web.

And I think I might be in luck. Taking a look at the kind of AJAX-y stuff the That Conference home page is accessing using the Chrome Developer Tools, it looks like the site exposes an OData API.

Let’s see what we get at thatconference.com/odata/api.svc/?$format=json.

Mmmm, Sessions. That sounds good. I’ll have that. Let’s see what’s behind thatconference.com/odata/api.svc/Sessions?$format=json.

Data. Just as I thought. Let’s get this sweet, sweet data in our page using our old friend jQuery.

We replace our “hello world” hero box with

1
<ul id="sessionList" class="list-unstyled"></ul>

and get the sessions using a jQuery $.ajax call with JSONP:

1
2
3
4
5
6
7
8
9
10
11
12
13
<script type="text/javascript">
    $.ajax({
        url: "http://www.thatconference.com/odata/api.svc/Sessions?$format=json&$callback=?",
        dataType: "jsonp",
        success: function (data) {
            var sessions = data.d;
            var $sessionList = $("#sessionList");
            $.each(sessions, function(index, session) {
                $("<li></li>").text(session.Title).appendTo($sessionList);
            });
        }
    });
</script>

Tangent: JSONP

For security reasons, browsers don’t allow AJAX requests to different domains than the current page. This is a good thing, but what if you want to do something legit like show recent tweets or load some conference sessions. JSONP is a clever trick for doing that. While you can’t do AJAX requests to any old domain, you can load JavaScript from any old domain.

JSONP says, “If I add a <script> tag to this page with the URL of a remote API I want to call and I also provide it the name of a callback function, you (the remote API) promise to return valid JavaScript invoking that function with the data I’ve requested.”

JSONP/OData Caveat

JSONP is not part of the OData spec, however JSONP support can easily be added to a WCF Data Service which natively supports OData. It just so happens that thatconference.com/odata/api.svc is one of these.

Result

It’s a pretty bland and useless list of sessions. But we’ll change that.

In the next post, we’ll add a proper view model with KnockoutJS and see what we can do with Bootstrap to improve our style.

AngularJS-ish filters in KnockoutJS

| Comments

As I learn more about AnuglarJS, I find filters to be one of the most exciting features of the framework. Filters allow common, mostly-simple display-level modifications to expressions in a view without having to include that logic in the model (i.e. $scope).

Applying a filter to an expression in an Angular view is super easy: {{ expression | filter }} and you’re done. Angular comes with a handful of filters for scalar values (number, currency, date) and arrays (filter, limit, order) but it’s also pretty easy to write your own.

In addition to “write once, use everywhere” convenience, filters are also chainable. This is particularly useful with Angular’s array filters: {{ customerList | filter:searchText | orderBy:'earnings' }} works just like it reads (only show customers with a property value containing the value of the model property searchText and then order those customers by the earnings property). And of course it live-updates when you change searchText.

OK, so Angular is awesome. But what if I’ve already done a bunch of stuff using another library (KnockoutJS in my case)? Can I do something like a filter in Knockout? Hint: yes.

Knockout has two ways that this could work: “fn” functions and extenders.

How fn works

Each of Knockout’s subscribable types exposes a public fn object to which you can add new functions to extend that type with cool new stuff. From then on, that stuff will be available on any new instance of that type. You can add new functions to any of the following:

  • ko.subscribable.fn
  • ko.observable.fn
  • ko.observableArray.fn
  • ko.computed.fn

And because of inheritance, functions that you add to a type will be usable by objects of any of its derived types. We’ll see why this is great for filters in a second.

Filters with fn

So how do we turn this into something like filters? Take a look at this fiddle.

You can see that I’ve added 4 functions to ko.subscribable.fn:

  • filter to filter an array by a string value
  • orderBy to order an array by an element property value
  • currency to format a number as currency
  • date to format a date

Why ko.subscribable.fn?

Why not put filter and orderBy on ko.observableArray.fn and put currency and date on ko.observable.fn? Simple: adding these functions to ko.subscribable maximizes chainability.

Let me explain. First, you want to return a ko.computed from filter functions. This ensures automatic UI updates because Knockout tracks subscribables accessed in the function body of a ko.computed and automatically re-evaluates the function when any of those values changes. But a ko.computed is not an observable or an observableArray. It is a ko.subscribable, though. So adding these functions to ko.subscribable.fn allows the inclusion of clear, chainable filters in data bindings like this one: data-bind="foreach: dudes.filter(search, 'name').orderBy(orderBy)".

It even makes sense to put the scalar (currency and date) filters on ko.subscribable.fn in case you ever add a filter (or filters) that whittles an array to a single value (i.e. first, last, findOne, imFeelingLucky, etc.).

By putting filter functions on ko.subscribable.fn, they are available to all subscribable types, giving you lots and lots of flexibility.

How extenders work

Extenders and fn are really similar. To create and use an extender, throw in some code like this:

1
2
3
4
5
6
7
8
9
10
11
12
ko.extenders.awesomeSauce = function (target, options) {
  
  //target is the subscribable object you are extending
  // add stuff to it and you can use it in your viewModel and bindings

  //options is the object provided to the initialization of the extender
  // use it to control what to add or how those additions behave
  
  return target; //if you don't return target, you might lose track of it
};

foo = ko.observable().extend({ awesomeSauce: { thing1: true, thing2: false }});

Ultimately, there’s little difference between fn and extenders as far as the end result is concerned. They both allow you to extend a subscribable. These are really the only differences:

  • You have to (or “can be”) be more explicit when you want to add extenders to a subscribable by calling .extend(). No automatic inclusion as with fn.
  • You can (or “have to”) provide options when you add an extender. This allows you to be more precise about what exactly your subscribable is extended with or how that stuff behaves.

Filters with extenders

In the fiddle above, instead of putting all the filter functions I might want to use into the same bag, they are separated by extender name.

ko.extenders.arrayExtensions is used to extend an observableArray with the filter functions filter and orderBy. These functions work exactly the same as in the fn example. However, in order to make the arrayExtensions methods chainable, I have to return a subscribable extended with arrayExtensions. This could be easy to forget to do when writing your own filter function. Also, this approach to chainability is not a frugal use of memory since two new functions are added to the target each time you call extend({ arrayExtensions: true }).

ko.extenders.formatting is used to extend an observable with filter functions that are appropriate to its data type (either "date" or "currency", provided as the extender option). Due to their simplicity, I did not make these filter functions chainable. I suppose they could be, but I couldn’t think of a good reason to do that here.

To reiterate, in order to take advantage of these filter functions, I have to call .extend() for my amount, date, and dudes observables.

Discussion and Gotchas

You can see that there is no difference between the fn and the extender approach in how the data-bind attributes in the HTML consume our filter functions. That’s pretty cool.

1
2
3
4
5
6
7
8
9
10
11
12
13
<input type="text" data-bind="value: search, valueUpdate: 'afterkeydown'" />
<select data-bind="value: orderBy">...</select>

<table class="table">
    ...
    <tbody data-bind="foreach: dudes.filter(search, 'name').orderBy(orderBy)">
        <tr>
            <td data-bind="text: name"></td>
            <td data-bind="text: amount.currency()"></td>
            <td data-bind="text: date.date('dddd MMMM Do YYYY')"></td>
        </tr>
    </tbody>
</table>

While it’s convenient for all functions you add to fn to be available to all subsequent instances of that type, ALL functions you add will be available to instances of that type. In the examples above, I added all my functions to ko.subscribable.fn to maximize chainability, but that small set of functions is already mutually-exclusive. filter and orderBy only make sense for observable arrays, currency only makes sense for numbers, and date only makes sense for dates. They are all there whether they make sense to be or not. Fortunately this is not a big concern for performance or scalability because each fn function object is shared by every subscribable.

Also, with the fn approach, putting everything in the same bucket is nice for availability, but if you start defining lots of fn functions in multiple files and possibly loading different subsets of those files on each page, you need to be pretty good at keeping those things straight, using unique function names, and keeping function names meaningful as to which date type they should be used for.

Chainability is powerful, but it can lead to long filter chains. In life, as in Knockout, you don’t get money for nothing and chicks for free. Because we have used ko.computed at each step of the way, a change at a point in the filter chain will cause re-evaluation of the remainder of the chain. If you have 10 filters chained together and you’re wondering why your page is sluggish, look there first.

I mentioned this above, but I wanted to reiterate it. Using the extender approach can be costly for memory consumption. Each time you .extend() a subscribable, new functions are added to the target. If you end up extending hundreds or thousands of objects on your page, you might start feeling the pain.

You may have noticed that arrayExtensions does not use its options parameter so it does not matter what the value is, but in order to call .extend() with valid JSON, a value must be provided. For no particular reason, I chose to provide true.

Conclusion

I hope this was a useful demonstration of the power of fn and extender functions in KnockoutJS. In summary, if you are looking for simplicity and ease of use with respect to filtering, I’d say go with fn functions. If you need more precision but perhaps don’t care as much about convenience, try extenders.

Enjoy, and let me know what you think!

I Have A Blog?

| Comments

Somebody: “Hey, look over there. It’s a blog.”
Everybody: “Oooohhhhh!”
Somebody (maybe somebody else): “A developer blog!”
Everybody (again): “Wooowwwww!”

Notwithstanding the widespread, public fanfare that accompanies the debut of a developer blog, it’s my first day and I really don’t know what I’m doing here. So to get started I went to the font of blogging wisdom, Scott Hanselman, and found “Your Blog is the Engine of Community” which made me feel like:

Then I found “Personal Branding for Software Developers” and it made me feel a little like:

Building my personal brand? Maybe. I did make a sweet logo in Paint.NET and brought in some snazzy web fonts. Incidentally, Google Fonts is a great way to waste several hours. Let’s stick with the hippy-dippy, free-love blogging advertized by Mr. Hanselman.

My goals for this blog are these:

  • Be helpful. While I want this blog to be a container for my passion for software development, I also want what I put out there to be useful to somebody (maybe even somebodies). If I can solve a problem, that means another developer doesn’t have to. Everybody wins and it’s good karma.
  • Get better. I know some things, but I don’t know a lot of things. Aside from the personal and technical growth that will come from the process of preparing my words and bits for all to see, I love collaborating with and learning from people who know more than I do.
  • Avoid TL;DR. No matter how interesting a post is, it’s frustrating to read for 10 minutes, only to realize you still have a ways to go. I’ll try to blow your mind, but keep it quick.

I hope you read and enjoy what is to come and I encourage your feedback!

Thanks to Ryan Niemeyer for the help in getting this set up.

A Little About Me

I’ve been a software developer for 9 years, doing web development for most of that time. For a number of years I worked on an application using ASP.NET, C#, and SQL Server. Since the emergence of JavaScript in recent years, I’ve done a lot more work on that front, especially with jQuery (obvious, right?), KnockoutJS, and even Vanilla JS. There are many more frameworks and libraries that are interesting to me, but for which I have yet to scratch the surface, so I’m excited to use this blog as a venue for those adventures.

I’m also lucky to be a husband and father to two special ladies and one furry one.