Global JavaScript Events with jQuery

When building web applications with sophisticated client-side behavior (i.e., you have a lot of JavaScript) I work hard to define loosely-coupled JavaScript modules. Intentional developers strive for structured and modular server-side code, but because of JavaScript’s history we tend not to take the same care with it. We then repeat the sins of the past when we find ourselves with hundreds or thousands of lines of JavaScript that aren’t encapsulated and decoupled.

Key Point: Write loosely-coupled JavaScript modules within your application.

Of course, you do need some coupling between modules. To realize the interactions that must occur between JavaScript modules, consider using a global event technique. Modules publish information to the world when something interesting happens; other modules subscribe to information they need to react to.

Key Point: Publishers shouldn’t need to know anything about their subscribers.

Here are a few ways to set up a global publish/subscribe mechanism your JavaScript modules to use:

Roll Your Own

We don’t want to succumb to the “Not Invented Here” problem, but these few lines create a simple but useful window.Bus object that supports global events.

(function() {

    var subscriptions = null;

    window.Bus = {

        reset: function() {
             subscriptions = {};
        },

        subscribe: function(messageType, callback) {
            if (typeof subscriptions[messageType] === 'undefined') {
                subscriptions[messageType] = [];
            }
            subscriptions[messageType].push(callback);
        },

        publish: function(messageType, args) {
            if (typeof subscriptions[messageType] === 'undefined') return;
            var subscribers = subscriptions[messageType];
            for (var i=0; i<subscribers.length; i++) {
                subscribers[i](args);
            }
        }

    };

    window.Bus.reset();

}());

// Subscriber usage:
window.Bus.subscribe('UserCreated', function(user) {
    alert('User ' + user.Name + ' created!');
});

// Publisher usage:
var newUser = { Name: "The Hulk" };
window.Bus.publish('UserCreated', newUser);

jQuery

One quick way to get there without adding any more dependencies than you probably already have is it just use features jQuery’s eventing system. Here’s code that demonstrates how to use jQuery as a global pub/sub framework. In this example, there are two modules, a publisher and a subscriber, each with a bit of HTML and a bit of JavaScript. The JavaScript comments explain the main points.

<html>
<head>
    <title>Client-side Pub/Sub with jQuery</title>
    <!-- add reference to jQuery -->
</head>

<body>

    <div>
        <input id='PublishButton' type='button' value='Publish' />
    </div>

    <b>Events:</b>
    <div id='Subscriber1'>
    </div>

</body>

<script type='text/javascript'>
// This function block correlates with the publisher's scope.
$(function() {

    // Represents a secret value only the publisher knows about directly,
    // but will include in its event args.
    var someNumber = 7;

    // When the button is clicked we publish an event.
    $("#PublishButton").click(function() {
        var dt = new Date();
        //
        // The next line is the important one; notice how the event args
        // are passed as an array.
        //
        $.event.trigger('CustomEventName', [someNumber, dt]);
        someNumber++;
    });

});

// This function block correlates with the subscriber's scope.
$(function() {
    //
    // Notice how we're not calling bind() on the subscriber like a typical
    // jQuery event, but calling it on our own UI component.
    // Also notice how the event args, which were published as an array,
    // are flattened into individual parameters.
    //
    $("#Subscriber1").bind('CustomEventName', function(event, number, date) {
        $("<div>").text("Event published: " + number + " @ " + date).appendTo($(this));
    });
});
</script>

</html>

Use a Global Event Library

The following JavaScript libraries are a few that provide a global pub/sub infrastructure:

Posted in JavaScript | Leave a comment

SQL Snapshot Notes

Sometimes when testing you need to repetitively restore a database back to a certain point in time. For very large databases the regular SQL restore can take quite a while. It seemed to me that using snapshots instead of regular backups cut this restore down quite a bit.

To Create the Snapshot

create database [NewDatabaseName] on (
    name = [SourceDatabaseLogicalName],
    filename = '\file\to\create\snapshot.ss'
) as snapshot of [SourceDatabase]

To Restore the Snapshot

-- force choke close any connections
alter database [SourceDatabase]
    set single_user
    with rollback immediate

go

-- restore from snapshot
restore database [SourceDatabase]
     from database_snapshot = 'NewDatabaseName' 

Notes

  • NewDatabaseName: The name of a database that doesn’t exist yet, but will be created and store the snapshot information.
  • SourceDatabase: The name of the database you want to create a snapshot of.
  • SourceDatabaseLogicalName: The “logical name” of the main MDF file for the database you want to create a snapshot of. In SQL Management Studio, do right-click/Properties for the database, and look here:

image

Posted in CodeMinder, SQL | Leave a comment

VB.NET Logical Operators

Quick chart to clarify which VB.NET operators one should use always.*

Never Use Instead, Always Use:
IIf(x, y, z) If(x, y, z)
And AndAlso
Or OrElse

 


* Always means “pretty much always.” There may be some very rare, strange cases to use the “never use” items.

** Logical Awesome image copied from this site.

Posted in Programming, VB | Leave a comment

The Speed of Trust: Individual Credibility

The Speed of Trust appears from here to be broken down into Five Waves of trust; these waves move from the inner-most out. That is, it begins with changing yourself, then working out to the people you interact most often with, and continuing out to society at large:

  1. Self trust.
  2. Relationship trust.
  3. Organizational trust.
  4. Market trust.
  5. Societal trust.

An introduction to “Self Trust” came next; that topic itself is broken down into four main cores. Self Trust comes down to credibility – are you a credible person? Even though people will give a simple Yes or No, or could give an answer on a one to ten scale for this, the book argues that there are four aspects of credibility, and your achievement in each of the four cores can vary:

  1. Integrity. This relates to basic honesty, but goes further into having an understanding of your own values, and the courage to stand up for and live by your values when challenged.
  2. Intent. Are your motives and agendas (and the behavior they produce) guided by a genuine care for others, or do you operate in a self-centered way without regard to others? Imagine someone who was very honest, but had no deep concern at all for others. Even though such a person would never tell a lie, people can’t trust the person because they always have to guard themselves so as not to be taken advantage of.
  3. Capabilities. What are your talents, abilities, skills, knowledge, etc., that allow you to produce results? Again, imagine someone full of honesty and integrity, and always operating with the very best of intentions, yet utterly incompetent in any tasks they were given. Such a person, though possessing a wonderful character, would still not be trustworthy simply because of incapability.
  4. Results. Do you have a track record of accomplishing tasks? Do you work on the right thing, and see that right thing through till it’s done? Again, one can imagine a talented, fully capable individual full of integrity and the good intentions, yet they never seem to Get Things Done. Such a person’s credibility would certainly be in question.

It’s is interesting to hypothesize an individual who has any three of the four cores of credibility listed above, but severely lacking the last.

When an expert witness is called to testify in a trial, the supporting lawyer will try to establish before the jury these four aspects; if the opposing attorney can seriously undermine the expert in any one of these items then the witnesses credibility, and the expert’s influence on the entire trial, is severely effected.

The next sections of the book drill down on each of the four cores individually. I’m in the process of building a Prezi presentation to map the structure of the book and keep its outline straight in my mind.

Posted in Leadership, Softer Skills | Tagged | Leave a comment

Why is Estimating so Hard?

Uncle Bob suggested a small software estimation exercise in a recent blog post, Why is Estimating So Hard?

My best-case, nominal, and worst-case estimates were x, 2x, and 4x, respectively. My actual time spent was 3.4x, and while the final code worked I wasn’t real happy with it.

I had never thought before about the distinction between how long it takes to do something and how long it takes to describe how to do something. Uncle Bob uses the example of tying shoes – takes a few seconds to do, but I’ve heard of college communication classes being centered around how to describe how to do it. Everyone failed that assignment.

The accounting world would have other similar examples. How long does it take to reconcile a checkbook, assuming no major discrepancies? Compare that with how long it would take to write a step-by-step procedure describing how to reconcile a checkbook — one that could be used by someone who didn’t have any familiarity with checkbooks.

In some ways, that’s what computer programming is: writing detailed, step-by-step procedures for a machine — and this machine has absolutely zero intelligence on its own — no problem solving skills, no deductive capabilities and no intuition.

Posted in Estimating, Programming | 2 Comments

Book: Notes to a Software Team Leader

I heard about this new book, Notes to a Software Team Leader, on a podcast on my way to work this morning. Below is the “Manifesto” of the book; upon reading it I feel the book has potential to have insightful and helpful content – I think it aligns with Nexus’s values in unique and surprising ways.

  • We believe the role of a team leader is to grow the people in their team
    • We believe in adjusting the leadership style to the current needs of the team, over a single style of leadership
    • We believe in challenging ourselves and our teams to always get better, so:
      • We embrace taking risks for our team over staying safe
      • We embrace fear and discomfort as learning new skills
      • We embrace experimentation as a daily practice
        • With people
        • With tools
        • With processes
        • With the environment
    • We believe team leaders lead people, not machines, so:
      • We embrace spending more time with our team than in meetings
      • We embrace learning people skills and techniques

This is a unique “book” – at least, it’s being written in a unique way. It’s not done yet, and if you feel you have something important to say about software team leadership, you can submit a contribution to the book.

Posted in Leadership, Programming, Softer Skills | Leave a comment

Giving Yourself a Job

In 1950 in New York, looking for a job consisted of catching a subway at 6:30 to pick up a copy of the New York Times, searching the classifieds, and then pursuing the most promising opportunities.

After doing this for forty weeks straight, Bill still didn’t have a job. Times were tough: meal time would come and there was no food; this lack created tension between Bill’s parents; the family was under tremendous discouragement.

Coming home after yet another grueling and fruitless day, Bill made a radical change. At the kitchen table with his brother Jerry, Bill said:

“If no one will give me a job, I’m going to give myself a job.”

Jerry thought his brother had finally lost it. There were no jobs to be had. It seemed ridiculous to magically produce one for yourself. But Bill was determined, and so the brothers pulled together all the money they had to start a business: $13.

After deliberating together they decided to start a technical writing company for $13 because you could buy pens and enough paper to get started on that budget. Bill said, “I’m going to sell. You’re going to go to the library and learn how to do technical writing.” Bill figured he could sell to companies of ten people or less who were doing government work.

In three weeks Bill made his first sale, and Jerry began putting his new tech-writing skills to work. The books were accepted. Within a few years they were able to hire a typist, then an illustrator, then rent an office in downtown New York (prior to that they all worked out of the brothers’ tiny apartment).

Today, sixty-two years later, this company has tens of thousands of employees. I had the opportunity to meet Jerry today, sixty-two years after he and his brother struck out on a $13 budget. I was very much impressed with this startup story. Through resourcefulness, fortitude, and hard work, Bill and Jerry created their opportunities. I believe the same opportunities exist today. Jerry had the library, where he could become a competent tech writer for free; today we have the Internet, where you can become a competent almost-anything for free. Your chances of becoming a multi-millionaire are probably low, but the reward for initiative, hard work and perseverance in today’s world is what is was in 1950: success.

Bill’s decision that he would not be ultimately dependent on others, but would take responsibility for improving his situation himself, is an admirable attitude. I wonder how many today carry that same attitude: “If no one will give me a job, I’m going to give myself a job.”

Posted in Business, Leadership | Leave a comment

From .NET, Calling REST and getting "dynamic" results

It seems like every time I want to call a RESTful service from my .NET app I have to re-lookup the documentation for either Hammock or RestSharp. Mainly for my own future reference, here’s the code using Hammock to get a change list from bitbucket.org’s REST API, then using JsonFx to deserialize the JSON to a dynamic object (which is pretty sweet).

var client = new Hammock.RestClient {
    Authority = "https://api.bitbucket.org",
    VersionPath = "1.0",
    Credentials = new BasicAuthCredentials {
        Username = "bitbucket-username",
        Password = "bitbucket-password"
    }
};

var request = new RestRequest {
     Path = "repositories/[username]/[repo]/changesets",
     Method = WebMethod.Get
};

dynamic result = new JsonFx.Json.JsonReader().Read(response.Content);
for(int i=0, len=result.changesets.Length; i<len; i++) {
    var date = DateTime.Parse(result.changesets[i].utctimestamp);
    string author = result.changesets[i].raw_author;
    // do what you want with the results.
}
Posted in CodeMinder, JSON, Programming, REST | Leave a comment

Call a web service with PowerShell

I recently used a PowerShell script like the following to troubleshoot the details of a third-party web service our code was using. I thought the script was something worth noting here for future reference.

$url = "https://path/to/Service.asmx"
$parameters = '<?xml version="1.0" encoding="utf-8"?>' + "`n"
   + '<soap12:Envelope...>(your request body here)</soap12:Envelope>'

$http_request = New-Object -ComObject Msxml2.XMLHTTP
$http_request.open('POST', $url, $false)
$http_request.setRequestHeader("Content-type", "application/soap+xml")
$http_request.setRequestHeader("Content-length", $parameters.length)
$http_request.setRequestHeader("Connection", "close")
$http_request.send($parameters)
$http_request.statusText
$http_request.responseText

 

The (your request body here) part can be obtained easily if the service you’re talking to is running on .NET with the metadata information turned on. If you point your regular web browser at the URL in this case, it will return a list of operations the service supports. Clicking on any operation will show you what to put in for $parameters – something like this – very handy:

image

Posted in PowerShell, REST | Leave a comment

The Speed of Trust: Chapter 2

There were two points in the second chapter of The Speed of Trust that had an impact on me.

Stewardship and Accountability

I learned in this chapter that the Stephen Covey who wrote this book is the son of the Stephen Covey who wrote the popular Seven Habits book. In Seven Habits, the father tells the story of teaching his son to take care of his yard. In The Speed of Trust we get to hear that very son tell his side of the story. I enjoyed seeing this story from those different perspectives. The son’s main point was that when his father entrusted the keeping of the yard to him, that trust inspired him to become trustworthy. The main aspects of this story that I found instructive were:

  • Clear stewardship. The father said the grass was to be kept “green and clean.” He showed in detail by example what both of those words meant.
  • Defined accountability. The father explained that once a week they would walk through the yard together to see how well the son was keeping the yard green and clean.
  • Autonomy of the “steward.” The father explained that the son was to use his own plan, his own timeline, his own resources, his own ideas to carry out his stewardship. The father didn’t give him detailed instructions, and wasn’t going to be reminding him and driving him to get the work done.
  • Sufficient equipping. The father said he would be willing to help if the son needed it. It was clear that the son would need to ask for it, but all the resources of the father would be available to the son to be successful in his stewardship.
  • Allowing failure. Things didn’t go perfectly right away; the son neglected his duties for a while. Yet the father honored the son’s autonomy by not nagging on him to get to work. The time of reckoning came, of course, at the agreed upon appointment when the accounting came. There were tears at this accounting, but the agreement continued, and the father dealt with things in a way that lead to the son learning how to keep the yard green and clean.
  • Trust created trustworthiness. In this book, Covey’s primary emphasis was that when you entrust something to someone, just the very act of entrusting someone with the responsibility can inspire them to become more trustworthy. (Of course one can take this to naïve and foolish extremes.)

The story in the book that illustrates these things adds a lot of meaning to these points. I am going to try to put this into practice with my kids and their chores and schoolwork. At this point we are homeschooling our kids, and a few of them wear their mother out because she has to keep riding them to keep on their work. I think a system like this may help – to tell them, “It’s no longer your mother’s job to make sure you get your work done. It’s your job. And every other evening you have an appointment with me, where you will give an account of where your schoolwork and chores are at.”

Trust = Character + Competence

It seems very true to me. When we trust someone in a particular circumstance, we have to trust both their character and their competence. Other ways to describes these are integrity and intelligence; personal trust and expertise trust; heart and head.

Consider that a person can be a wonderfully nice and honest person who never breaks the most minute law, always holds doors for ladies and helps the elderly. But if that person is not a very good carpenter, you’re not going to trust him to build the shed in your back yard. For specific circumstances, character is not enough; competence is necessary.

The reverse is certainly true: you can have the most proficient carpenter in the world, but if he’s a liar and a cheat and has a dangerous temper, you’re not going to want to work with him, either.

I found the examination of the two facets of trust to be very clarifying to my own thinking.

Posted in Leadership, Softer Skills | Tagged | 6 Comments