Null !== Steve

Steve Gentile's Tech Blog – Thoughts and Musings

Simple Dojo Example – require, declare (class), and modules

I’ve been exploring the Dojo Toolkit this weekend after looking at some examples that Cesium (Sandcastle example) ships with.  There are many good examples and tutorials on the Dojo website to get yourself familiar with Dojo and up to speed.  Dojo has been around for quite some time, but it’s evolved – at the time of this writing I’m using version 1.9.

I’m a fan of RequireJs  – so to see that Dojo is built upon the same AMD concept as RequireJs is quite intriguing to me!  RequireJs allows for better structured JavaScript using concepts such as ‘dependency injection’ that many OO programmers are aware of.

Let’s jump into an example of how to use Dojo!  My example is built on two dojo tutorials (Introduction to AMD Modules and Classy Javascript).  To keep things simple and interesting, I’m using NodeJS to run this sample.  (All the source code for this post can be pulled down from my github repository).

Just to get this out of the way – let’s get our environment setup.  If you haven’t already, make sure you have NodeJs installed.  Keep in mind, NodeJs isn’t required to actually run this code, you can use any web server.   Create a new directory – ie. ‘modules’ and then enter the command ‘npm install connect’.  Node Connect is a simple and quick way to fire up a web server.  You should now see a ‘node_modules’ directory inside our modules folder.  The next step is to create our server – created a server.js file in the modules folder.  The code should look like this:

   1:  var connect = require('connect');
   2:  connect.createServer(
   3:          connect.static(__dirname)
   4:          ).listen(8080);
   5:  console.log('server running on port 8080');

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

Node makes it quite easy to get up and running, so this should be enough for our web server!  Let’s move on to what we came here to do!

As mentioned above, you can get the source code from my github repo – but lets take a look at the project structure:

image

As you can see, I have a ‘app’ folder with two javascript files.  The index.html will contain the code to run our simple example.  Let’s take a look at our index.html file:

   1:  <html>
   2:      <head>
   3:          <link rel="stylesheet" href="style.css" media="screen">
   4:          <script 
src="//ajax.googleapis.com/ajax/libs/dojo/1.9.0/dojo/dojo.js"></script>
   5:          <script>
   6:              require([
   7:                      "app/counter.js", "app/logger.js"
   8:                  ], function(counter, Logger){
   9:                  var log = new Logger();
  10:                  log(counter.getValue());
  11:                  counter.increment();
  12:                  log(counter.getValue());
  13:                  counter.decrement();
  14:                  log(counter.getValue());
  15:              });
  16:          </script>
  17:      </head>
  18:      <body>
  19:      </body>
  20:  </html>

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

As you can see, I’m supplying our main dojo.js file via CDN.  The next section here in the script tags is our application (normally I’d even have this code in a separate .js file – but for now this will suffice).  We wrap our code up in our ‘require’ statement.  The first part of this is an array of strings for each dependency our application has.  In this case, we have a dependency on ‘counter.js’ and ‘logger.js’.  The function that follows matches our two dependencies and provides access to that code, ‘counter’ and ‘Logger’.  In this example we can see that one is a ‘static’ object whereas the other is an object we will create. As you can see, this helps keep our code rather clean, the rest of the code.

Let’s take a look at the ‘counter.js’ code first – as it’s the simplest to follow:

   1:  define(function(){
   2:      var privateValue = 0;
   3:      return {
   4:          increment: function(){
   5:              privateValue++;    
   6:          },
   7:          decrement: function(){
   8:              privateValue--;
   9:          },
  10:          getValue: function(){
  11:              return privateValue;
  12:          }
  13:      }
  14:  });

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Dojo provides some good structure for us to create our modules.  In this case, we are wrapping our code in a ‘define’ function which tells Dojo this is a module and will be accessible from our application.   Dojo will handle loading and injecting this module into our main application. 

The second module this application uses is our ‘logger.js’ file.  This code takes a next step by wrapping our code in an object, aka class:

   1:  //create a new class
   2:  define(["dojo/_base/declare",
   3:          "dojo/_base/window", 
   4:          "dojo/dom-construct",
   5:          "dojo/dom"
   6:      ], function(declare, win, domConstruct, dom){
   7:          return declare(null, {
   8:              log : function(msg){
   9:                  if(!dom.byId('console')){
  10:                      domConstruct.create('div', {id:'console'}, win.body());
  11:                  }
  12:                  dom.byId('console').innerHTML += "<div>" + msg + "</div>";
  13:              }
  14:      });
  15:  });

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, “Courier New”, courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

The define in this example has some additional dependencies.  All four of these dependencies comes from the dojo framework.  This really shows how modular dojo is and how easy it is to cleanly separate your apps concerns  (Initially when building this application, I had this code in the index.html, then refactored it out to keep the index.html code very clean!).

This code introduces a second concept – that of ‘declare’.  To understand and see how to use ‘declare’ – take a look at the Dojo ‘live docs’ definition.  This particular object will expose a ‘log’ function.  Other libraries try to mimic a ‘class’ definition (aka Typescript, Backbone, etc..) whereas I believe through Dojo’s ‘declare’ it’s more in line with how most people write javascript today.   Since we aren’t creating the object in this code nor returning an object literal, the ‘return declare’ will allow the caller to instantiate the object. 

The live docs link above to declare provides good documentation with several examples.  I appreciate the inheritance and mixin capabilities of declare.

This should wrap up this post – I hope to share more as I further explore using Dojo with Require.  If you have any questions or feedback please share!

(Just a side note: I’ve been using KnockoutJS on several applications and recommend taking a look at the DurandelJS framework that creates a RequireJS/AMD application structure around KnockoutJS – you can see the power of using RequireJs/AMD).

KnockoutJS & ASP.NET Mvc Partial View Loading

Recently I’ve needed to dynamically load ‘partial views’ that are bound to KnockoutJS view models.  The application is a single page app approach, composite application where I’m loading a particular view.

Retrieving the ‘partialView’ is rather simple with ASP.NET Mvc:

image

This is rather straightforward.   I make the call to retrieve the template with a jQuery ajax call:

image

I create my viewmodel, and my viewmodel has a property with the partialViewName defined – ie. self.partialViewName = “_SomePartialView”;

This works very well so far – I have some caching of the html partial, although I might remove this and just takes a more server side ‘get’ ‘varybyparam’ caching on the controller action.

Previously I had an approach like this:

<div data-bind=”with: myViewModel”>
@Html.Partial(“_SomePartialView”)
</div>

Which I still believe works good for one or two scenarios – but the number of viewmodel objects (I have 20+ views here getting loaded) let me change my approach to more of a ‘load on demand’.  I’m pretty happy with this!

Update: one of my concerns that I meant to research and apply here is the impact of loading vm’s to the same dom node with applyBinding and memory leaks.

A good response to this on stack overflow: http://stackoverflow.com/questions/10048485/how-to-clear-remove-observable-bindings-in-knockout-js/10049722#10049722

So what I do for this is use the ko.cleanNode prior to re-applying this binding to the same node:

image

Simple Quick Git Common Actions

Create Branch:

Switch to a new branch:

git checkout -b branch-name

Shows the branch your on highlighted by *

git branch

Add files – marks any files to be added

git add .

Check-in changes

git commit -a -m “message”   //I always use the -a even with the git add . usage

Merge (to master)

switch back to the branch you want to merge to

git checkout master

specify the branch you want to merge from

git merge branch-name

optional – remove that branch

git branch -d branch-name

to completely abandon a branch:

git branch -D branch-name //only if you really screw things up

Revert – or rather we can still undo the changes easily by having Git check out the previous commit with the checkout command (and a -f flag to force overwriting the current changes):

git checkout -f

 

Extra Content

Heroku

This is definite OT but to add a few bonus items :)

Initial creation (this assumes you setup heroku):

heroku create --stack cedar
Deploy:
git push heroku master
(if using rails: heroku run rake db:migrate)

Static Properties and Methods with Coffeescript

class Person
   @test: (input) ->
      return input
   @staticProperty : 10
   @get: ->
     return {name:'Steve'}
   nonStatic: ->
     return "non static"

console.log Person.test 'Hello World'  #result is 'Hello World'
console.log Person.get() #result is object
console.log Person.staticProperty   #result is 10

#console.log Person.nonStatic()  this is an error
person = new Person()
console.log person.nonStatic() #result is 'non static'

Should be fairly explanatory :)

KnockoutJs : Toggling CSS class

A common scenario with Javascript is toggling a set of elements based on the selected element add applying, removing css classes.  You’ll see this on menu items, etc… and in my case where we want to have styled ‘button’s instead of a radio list.

An example of this might be handling the selection of the button and then applying a class and removing any other classes, for example:

$(‘.year_item’).bind(‘click’, function(){
$(“.year_Item”).removeClass(“selected_year”);
$(event.currentTarget).addClass(“selected_year”);
});

In my first attempt at such a toggle with knockoutjs, I followed a similiar route – calling back to my viewmodel :

setYear: function (year, event) {
$(“.year_Item”).removeClass(“selected_year”);
$(event.currentTarget).addClass(“selected_year”);
myViewModel.year(year);
}

The binding in the html looks like this:

<ul data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.setYear” type=’button’/></li>
</ul>

This works fine.  However, I can do better – since KnockoutJs supports setting the CSS class on binding.

ie. <div data-bind="css: { profitWarning: currentProfit() < 0 }">

So let’s take this example and show how we can effectively toggle the CSS class based upon the value of the binding – using our example above:

<ul class=”bigButtons” data-bind=”foreach: years”>
<li><input data-bind=”text: $data, click: $parent.year, css:{selected_year: $parent.year() === $data}”  type=’button’/></li>
</ul>

That is it.  No more function required in the viewmodel.  To understand what happens here is to understand the $parent.year click event.  Basically in KnockoutJs 2.0 by default $parent.year takes the $data property as a parameter.  The year binding is set, which in turn triggers the css selection on all the items reevaluating if it should have that CSS appended.

This has proved to be very terse and valuable in our UI.

Edit: I’ve put an example out on jsFiddle: http://jsfiddle.net/sgentile/pRC4c/

KnockoutJS ‘Addons’, etc…

This is not intended to be a full post – just wanted to highlight a few links to add ons to the javascript knockoutjs library I’ve been using on some recent projects:

Observable Dictionary :  github source  gist of example

Protected Observable: blog post with sample code  gist of example

KO ‘Datagrid’ : link to google group post  github source  samples

I’ll update this with more links – it would be great to have a knockoutjs community

Steve Michelotti has a KnockoutJs course of Pluralsight and an example of building a custom binding

Also just to add – I have an example of KnockoutJS with NodeJs on my github here with a few simple tests using jasmine-node for some specs, and QUnit showing some Knockoutjs test scenarios.

JavaScript Todos–Backbone with asp.net mvc

There are certainly plenty of articles, examples, etc… around creating the ‘Todos’ sample.  To learn more about different frameworks and a more complete example, check out Addy Osmani‘s examples here: http://addyosmani.github.com/todomvc/   This is a fantastic resource to learn about different available frameworks.

Most of these examples tend to use the localStorage.  Not that it’s a big deal, but I wanted to put together something very very simple that showed some connections between using Backbone.js to make calls to a backend server.  In this case, I have decided to use asp.net mvc.

The example uses IISExpress to be hosted.  To reduce some of the friction, there is no database, just a static List object on the server.  I am not handling edits in this simple example – just a GET call to show todos and POST call to add a new todo.

To get an example – you can get it on github https://github.com/sgentile/MvcBackbone

First, this is not a ‘how to use backbone’ nor a ‘how to use asp.net mvc’ – I’d probably fail you on both subject matters!  The goal here is to highlight the aspects of backbone that help in making the connection to the backend server.  Backbone is providing an abstraction over the ajax calls.  You certainly CAN use ajax directly if you want. 

So, let’s get started.   The ‘todo’ model is quite simple – see todo.js line 5 :

Todo = Backbone.Model.extend({
    // Default attributes for the todo.
    defaults: {
      content: "empty todo..."
    },
        // Ensure that each todo created has `content`.
    initialize: function() {
      if (!this.get("content")) {
        this.set({"content": this.defaults.content});
      }
    },
    
    url: "home/todos"
});

If you check the backbone.js document for Model url http://documentcloud.github.com/backbone/#Model-url

Returns the relative URL where the model’s resource would be located on the server. If your models are located somewhere else, override this method with the correct logic. Generates URLs of the form: "/[collection.url]/[id]", falling back to "/[urlRoot]/id" if the model is not part of a collection.

The key here is to let backbone know the url for Todos.  We will be making a ‘save’ call on our Todo model object when we add a new model  ( save: http://documentcloud.github.com/backbone/#Model-save ).  This will look for the url on the server:

the save will be a "create" (HTTP POST), if the model already exists on the server, the save will be an "update" (HTTP PUT).

 

The TodoFormView on line 38, handles connecting the forum submit call to our save function, which maps the form to the Todo model.  Calling ‘save’ directly on the model results in an ajax call – ie:

TodoFormView = Backbone.View.extend({
    initialize: function () {
        this.template = $("#formTemplate");
    },
    events: {
        "submit #todo-form": "save"
    },
    render: function () {
        var content = this.template.tmpl();
        $(this.el).html(content);
        return this;
    },
    save: function () {
        var val = this.$("input").val();
        var model = new Todo({ content: val });
        model.save();
        this.$("input").val('');
    }
});

The key items to see here is the save function call  – where we save the model – model.save();

So the ‘home/todos’ matches up to the HomeController Todos action – with is a new Todo, so therefore it cooresponds to the following:

        [HttpPost]
        public ActionResult Todos(Todo todo)
        {
            todo.id = Guid.NewGuid();
            TodoList.Add(todo);
            return Json(TodoList, JsonRequestBehavior.AllowGet);
        }

As you see, backbone is handling the underlying ajax POST calls to the server!

Obviously GET calls are equally as straightforward.  I have a collection of Todos defined:

Todos = Backbone.Collection.extend({
    model: Todo,
    url: "home/todos"
});

I am able to do a GET call with ‘fetch’ as seen below:

TodoListView = Backbone.View.extend({
    initialize: function () {
        _.bindAll(this, "render");
        this.collection.bind("change", this.render);
        this.collection.bind("add", this.render);
        this.collection.bind("fetch", this.render);

        todos.fetch({ add: true });
        
    },
    render: function () {
        //clear out the existing list to avoid "append" duplication
        $(this.el).empty();
        //use an array here rather than firehosing the DOM
        //perf is a bit better
        var els = [];
        //loop the collection...
        this.collection.models.forEach(function (todo) {
            //rendering a view for each model in the collection
            var view = new TodoItemView({ model: todo });
            //adding it to our array
            els.push(view.render().el);
        });
        //push that array into this View's "el"
        $(this.el).append(els);
        return this;
    }
});

The key here is the todos.fetch call.  You can learn more about collections and fetch here: http://documentcloud.github.com/backbone/#Collection-fetch

This is all for now, should be a good start – there is much to learn here obviously (ie bootstrapping). 

Next time, I hope to share more about using backbone with asp.net mvc and then add jquery mobile to the mix.  Thanks!

JavaScript: Revealing Module Pattern and Namespacing

This is a basic post regarding namespacing and revealing module pattern.  When starting a new JavaScript application it’s important to have a good starting foundation.  First let’s show how to use namespacing in JavaScript:

window._ns = window._ns || {};

_ns is attached to the global window object.  Alex MacCaw in his book ‘’JavaScript Web Applications’ describes this well:

We’re setting on the window object to ensure that it’s globally accessible.

Also, by using this pattern, it’s easy to see which global variables a script is declaring,

just look through the script for window references

Let’s show this in use, first using what is referred to as the singleton pattern:

_ns.Singleton = {
    _somethingConsideredPrivate: function () {
        document.write("Singleton doSomething complete<br/>");
    },
    doSomething: function () {
        this._somethingConsideredPrivate();
    }
};

 

_ns.Singleton.doSomething();   //note, everything is public – some use an underscore : _privateFunction : function … to denote private, but it’s still accessible

<html>
<head>
    <title>Module</title>
    
    <script src="/Scripts/Module.js" type="text/javascript"></script>
</head>
<body>
    <div>
        <script>
            _ns.Singleton.doSomething();
        </script>
    </div>
</body>
</html>

But what if we want to use the revealing module pattern which gives us the concept of private and public ?

basically we return what is public.

_ns.RevealingModule = function () {
    var privateData = {
        message: "RevealingModule doSomething complete"
    };

    var privateFunction = function () {
        document.write(privateData.message);
    };

    var doSomething = function () {
        privateFunction();
    };

    return {
        //since returned - it's public:
        doSomething: doSomething
    };

} ();   //end of module

 

It’s usage pattern as follows:

<!DOCTYPE html>

<html>
<head>
    <title>Module</title>
    
    <script src="/Scripts/Module.js" type="text/javascript"></script>
</head>
<body>
    <div>
        <script>
            _ns.Singleton.doSomething();
            _ns.RevealingModule.doSomething();
        </script>
    </div>

</body>
</html>

If you try to access the private function – it would fail:

 

_ns.RevealingModule.privateFunction();

would result in:

_ns.RevealingModule.privateFunction is not a function
[Break On This Error] _ns.RevealingModule.privateFunction(); 

I hope this helps clarifying namespacing and the revealing module pattern.  There are certainly some great resources to describe both. 

Recommended reading followup: http://www.klauskomenda.com/code/javascript-programming-patterns

Alex MacCaw’s book ‘JavaScript Web Applications’: http://shop.oreilly.com/product/0636920018421.do

Javascript/jQuery contains and not contains sample

<div class="navigationelementsContainer clear_fix">
{{each navelement}}
        {{if name != 'null'}}                             
            <div class="navigatorModifier pointer" data-name='${name.toUpperCase()}' data-modifier='${modifier}'>${name} (${count})</div>
        {{/if}}                                   
    {{/each}}
</div>

$(".navigatorModifierSearch").live('keyup', function (event) {
            var $navigationelementsContainer = $(this).parent().parent().find(".navigationelementsContainer");
            var searchTerm = $(this).val();

            if (searchTerm.length > 0) {
                $navigationelementsContainer.find('div[data-name*="' + searchTerm.toUpperCase() + '"]').removeClass("hideNavElement");
                $navigationelementsContainer.children().not('div[data-name*="' + searchTerm.toUpperCase() + '"]').addClass("hideNavElement");                
            } else {
                //make sure all are showing
                $navigationelementsContainer.children().removeClass("hideNavElement");
            }
        });

https://gist.github.com/1207961.js

 

Key section:

$navigationelementsContainer.find(‘div[data-name*="' + searchTerm.toUpperCase() + '"]‘).removeClass("hideNavElement");

$navigationelementsContainer.children().not(‘div[data-name*="' + searchTerm.toUpperCase() + '"]‘).addClass("hideNavElement");

Not the best blog post.. but it’s pretty nice way to select elements by attribute with ‘contains’ as well as ‘not contains’ Smile

‘Restoring’ Git after Upgrade to OSX Lion

I was surprised to find out my ‘git’ command didn’t work after upgrading to Lion.

It is still there (verify by checking for this directory: /usr/local/git/bin), just needs to be mapped.

I was able to find out that the git installer uses paths.d to add it to the path.

I went to /etc/paths.d and did ls  – but there was not git file.

open Terminal

cd /etc/paths/d

sudo vi git

enter /usr/local/git/bin at the top of the file (if new to vim, hit ‘I’ to enter ‘insert mode’)

hit escape – type :wq to save and quit

open new terminal – run ‘which git’

Should work now

Post Navigation

Follow

Get every new post delivered to your Inbox.