Announcing Ember! Master Space and Time With JavaScript Book 4

You have no idea how happy I am to announce that Book 4 of Master Space and Time with JavaScript: Ember is now on sale. You can buy it at http://www.noelrappin.com/mstwjs

It’s not done, of course. But it’s off to a good start, and I think it’s going to be great. Here’s the state of the world:

  • Release 1 of the Ember book is $7, just like its recent siblings. The four book bundle is still $15.

  • Release 1 is about 20 pages of content (plus the same intro, acknowledgments, and so on). It covers setting up the Time Travel app with an Ember front end, then the basic concepts involved in getting data from the server, displaying it to the browser and responding to actions. We basically end at a chapter break, so it’s a contained example, though obviously the rest of the book will take it farther.

  • The code is written against Ember 1.0pre4, which means its current as of yesterday.

  • Unlike some of the other betas, this one has been reviewed by a few people, including people who know more about Ember than I do, so I’m pretty happy with how it’s going so far.

  • We don’t cover testing yet (in part because the framework does so much that there isn’t much logic to test yet). It’s coming, though. Trust me.

  • The plan is for basically weekly releases until done.

  • I don’t know how long this is going to get — to some extent it’s going to depend on the reception, more sales = more encouragement to write. It will be at least in the 100is page range as the previous books. If it gets much longer than that, I may raise the price at that time.

That’s the scoop. Buy it: http://www.noelrappin.com/mstwjs, enjoy it, spread the word.

Thanks

Functions that return functions are the luckiest functions in the world

Here’s some JavaScript:

var foo = function(a, b) { return a * b };

var bar = function(func) {
  return function() {
    return func.apply(this, arguments)
  };
};

baz = bar(foo);
console.log(baz(2, 3));

What we have here is a function, bar, that both takes a function as an argument and returns a function as it’s result. It’s transforming the function passed to it into a different function.

Okay, that’s cool in kind of an abstract way, but so what? Let’s play around with function that take and return functions to show off some potentially useful tricks.

I’ll note right here up top, that there are more complex, fully featured, and robust versions of all the things I’m showing here. I’m just playing with functions.

We can add diagnostics.

var foo = function(a, b) { return a * b };

var trace = function(func) {
  return function() {
    console.log("calling " + func);
    console.log(new Error("normal trace").stack);
    return func.apply(this, arguments)
  };
};

foo = trace(foo);
console.log(foo(2, 3));

All the trace function is doing here is logging a couple of things before actually calling the function — namely, it’s printing the function body (JavaScript doesn’t have a consistent way to get the function’s name), and a stack trace. The console output is:

calling function (a, b) { return a * b }
Error: normal trace
  at file:///Users/nrappin/Dropbox/coderx/blog/functions.html:8:17
  at file:///Users/nrappin/Dropbox/coderx/blog/functions.html:15:13

Okay, that’s kind of neat. You can also tweak it to do something like a Jasmine spy object, but it takes some object manipulation. Here we really start to take advantage of the fact that JavaScript functions are basically just JavaScript objects.

var foo = function(a, b) { return a * b };

var spy = function(func) {
  var returnFunc = function() {
    returnFunc.timesCalled += 1;
    returnFunc.args.push(arguments);
    return func.apply(this, arguments);
  }
  returnFunc.timesCalled = 0;
  returnFunc.args = [];
  return returnFunc;
};

foo = spy(foo);

console.log(foo(2, 3));
console.log(foo.timesCalled);
console.log(foo.args)

Same basic idea here, except we’re doing some dancing with scope to make sure we have access to all the variables we want to, when we want them. Specifically, rather than just returning an anonymous function, we’re giving it the name returnFunc. Inside the funtion body of returnFunc, we’re accessing properties of the returnFunc functional object itself. Specifically we’re incrementing a counter and adding to a list of called arguments.

After we define the function, we initialize the timesCalled and args properties, and return our functional object. This works because we can access properties of the functional object inside the function itself, which seems weird, but makes more sense if you think of it just as an ordinary object accessing other properties of the same object.

Here’s a related example — in this case, our function object has its own methods.

var benchmark = function(func) {
  var returnFunc = function() {
    returnFunc.startDate = Date.now();
    result = func.apply(this, arguments);
    returnFunc.endDate = Date.now();
    return result
  }
  returnFunc.elapsedTime = function() {
    return returnFunc.endDate - returnFunc.startDate;
  };
  return returnFunc;
}

foo = benchmark(foo);
console.log(foo(2, 3));
console.log(foo.elapsedTime());

In this one, we’re running the inner function surrounded by time stamps, and we’re adding a function to the function object, which again, seems weird. At the end, we can query a benchmarked function as to how long it takes. (Yes, I realize that the dev tools allow you to do this.)

Here’s one that might be more practical. Memoizing is the act of caching the results of function calls so that you don’t need to re-evaluate an expensive computation.

var memoize = function(func) {
  var returnFunc = function() {
    argsToCheck = (JSON.stringify(arguments));
    if (returnFunc.cache[argsToCheck]) {
      return returnFunc.cache[argsToCheck];
    } else {
      result = func.apply(this, arguments);
      returnFunc.cache[argsToCheck] = result;
       return result;
    }
  }
  returnFunc.cache = {};
  return returnFunc;
}

foo = memoize(foo);
console.log(foo(2, 3));

In this case, we hold on to the functional argument as before, but when we call the memoized function, we first compare the argument list against a cache. We’re using the JSON string version of the argument list, so we do have that conversion overhead. If this particular argument list has already been called, then we return the result of the previous call without recalculating. If not, we calculate the function, and place the result in the cache. So, our first call to foo in the example places (2, 3) in the cache, but the second call would retrieve it, to avoid that very expensive multiplication.

This is the beginning of manipulating functions in JavaScript — functional programming in general is a big topic, but worth looking at. Adapting a functional style where side effects and mutable state are downplayed in favor of manipulating functions, can really pay off in less complexity in your code.

Like this? You might like my book Master Time and Space With JavaScript, free sample available, and $15 for the whole thing.

Depending on jQuery and Perspective

The reported errata for Master Time and Space With JavaScript (buy it here) has been pretty light so far. A bunch of typos, some setup weirdness.

And one interesting issue worth exploring. What is a dependency, and maybe more to the point, where is a dependency?

This issue was raised by a reviewer whose name I’m not going to mention — that’s not a reflection on the reviewer, but rather a reflection on the fact that I’m going to put words in his mouth to expand on his brief comment on the issue, so my interpretation of his position may not actually be his position.

Anyway the reviewer had a comment about when to convert to and from jQuery objects. He raised it in the context of the autocomplete example from the please-go-pay-for-it Book 2, but it also applies to the toggler example in just-for-free Book 1, and really, in any case where you have a JavaScript object which uses a data type that is a jQuery object.

Here’s the deal. I have an object — in this case it’s my autocomplete selector, but I’ll pretend it’s a generic widget because the exact object doesn’t matter — which is being initialized via a function call like so.

    widget = new Widget({parentSelector: "#autodiv"});

The key point here being the parentSelector: "#autodiv" option. In the eventual constructor, that #autodiv is immediately converted to a jQuery object (The example in the book is more elaborate, I’m simplifying to focus on the issue at hand…)

    var Widget = function(options) {
        this.$domParent = $(options.parentSelector);
    };

The reviewer’s point was that he’d rather convert the selector to jQuery in the call to Widget and pass the argument to Widget already converted to a jQuery object, rather than have the Widget constructor do the conversion:

    widget = new Widget({domParent: $("#autodiv")});

    var Widget = function(options) {
        this.$domParent = options.domParent;
    };

I’m not convinced yet that one way is better than the other — I haven’t changed the book code, but I certainly respect this reviewer’s opinion on how to structure JavaScript. But I do think that the two options make different assumptions about the structure of the application that are worth teasing out.

In my structure, jQuery is treated as an implementation detail of the Widget. Since jQuery is an implementation detail, outside code wouldn’t be expected to know about it, so outside code communicates to the Widget via a selector. Now, I grant that there’s a little bit of fiction there, since the selector syntax is (somewhat) jQuery specific. If I really wanted to isolate jQuery, then the calling argument should just be the DOM ID, and the Widget would also be responsible for converting the DOM ID to a jQuery object, with the intermediate step of building a jQuery selector string:

    widget = new Widget({parentId: "autodiv"});

    var Widget = function(options) {
        this.$domParent = $("#" + options.parentId);
    };

The advantage of treating jQuery as an implementation detail of my widget is that the rest of my code does not need to know or care about it, and I can presumably even test other parts of my code without jQuery even being around. Also, if I choose to swap jQuery out for some reason, the rest of my code doesn’t need to know, only my widget needs to be changed. I would consider the conceptual point about jQuery being an implementation detail of the widget to be important even if I find it exceptionally unlikely that I would swap out jQuery. (For one thing, it also protects me against jQuery itself changing).

In my reviewer’s structure jQuery is a dependency of the application as a whole. Looked at from that perspective, it makes sense to convert everything to jQuery objects as early as possible, to maintain consistency of representation across the entire application. The code as a whole may be easier to read, since we aren’t continually having to worry about whether an object is a jQuery object or just some kind of DOM identification. If multiple widgets are all using the same jQuery object, then we might prevent some duplicate conversion to jQuery objects. This probably simplifies the internal code at the cost of making us more dependent on jQuery itself. As a practical matter, that tradeoff might be worth it — once we’ve decided to use jQuery, changing it is probably unlikely.

Essentially, it’s a question of where you draw your boundaries. I’m not sure there’s a long-term practical difference between these two structures, in that I don’t think one of them necessarily leads to better or more flexible code over time, especially given even rudimentary attention to practical details. But I do think you should be clear about which structure you are using — mixing the two by treating jQuery as a specific dependency of some parts of the code but a general dependency of other parts would probably lead to confusion later on.

Like this? Go ahead and read Master Time and Space With JavaScript

Depending on jQuery and Perspective

The reported errata for Master Time and Space With JavaScript (buy it here) has been pretty light so far. A bunch of typos, some setup weirdness.

And one interesting issue worth exploring. What is a dependency, and maybe more to the point, where is a dependency?

This issue was raised by a reviewer whose name I’m not going to mention — that’s not a reflection on the reviewer, but rather a reflection on the fact that I’m going to put words in his mouth to expand on his brief comment on the issue, so my interpretation of his position may not actually be his position.

Anyway the reviewer had a comment about when to convert to and from jQuery objects. He raised it in the context of the autocomplete example from the please-go-pay-for-it Book 2, but it also applies to the toggler example in just-for-free Book 1, and really, in any case where you have a JavaScript object which uses a data type that is a jQuery object.

Here’s the deal. I have an object — in this case it’s my autocomplete selector, but I’ll pretend it’s a generic widget because the exact object doesn’t matter — which is being initialized via a function call like so.

    widget = new Widget({parentSelector: "#autodiv"});

The key point here being the parentSelector: "#autodiv" option. In the eventual constructor, that #autodiv is immediately converted to a jQuery object (The example in the book is more elaborate, I’m simplifying to focus on the issue at hand…)

    var Widget = function(options) {
        this.$domParent = $(options.parentSelector);
    };

The reviewer’s point was that he’d rather convert the selector to jQuery in the call to Widget and pass the argument to Widget already converted to a jQuery object, rather than have the Widget constructor do the conversion:

    widget = new Widget({domParent: $("#autodiv")});

    var Widget = function(options) {
        this.$domParent = options.domParent;
    };

I’m not convinced yet that one way is better than the other — I haven’t changed the book code, but I certainly respect this reviewer’s opinion on how to structure JavaScript. But I do think that the two options make different assumptions about the structure of the application that are worth teasing out.

In my structure, jQuery is treated as an implementation detail of the Widget. Since jQuery is an implementation detail, outside code wouldn’t be expected to know about it, so outside code communicates to the Widget via a selector. Now, I grant that there’s a little bit of fiction there, since the selector syntax is (somewhat) jQuery specific. If I really wanted to isolate jQuery, then the calling argument should just be the DOM ID, and the Widget would also be responsible for converting the DOM ID to a jQuery object, with the intermediate step of building a jQuery selector string:

    widget = new Widget({parentId: "autodiv"});

    var Widget = function(options) {
        this.$domParent = $("#" + options.parentId);
    };

The advantage of treating jQuery as an implementation detail of my widget is that the rest of my code does not need to know or care about it, and I can presumably even test other parts of my code without jQuery even being around. Also, if I choose to swap jQuery out for some reason, the rest of my code doesn’t need to know, only my widget needs to be changed. I would consider the conceptual point about jQuery being an implementation detail of the widget to be important even if I find it exceptionally unlikely that I would swap out jQuery. (For one thing, it also protects me against jQuery itself changing).

In my reviewer’s structure jQuery is a dependency of the application as a whole. Looked at from that perspective, it makes sense to convert everything to jQuery objects as early as possible, to maintain consistency of representation across the entire application. The code as a whole may be easier to read, since we aren’t continually having to worry about whether an object is a jQuery object or just some kind of DOM identification. If multiple widgets are all using the same jQuery object, then we might prevent some duplicate conversion to jQuery objects. This probably simplifies the internal code at the cost of making us more dependent on jQuery itself. As a practical matter, that tradeoff might be worth it — once we’ve decided to use jQuery, changing it is probably unlikely.

Essentially, it’s a question of where you draw your boundaries. I’m not sure there’s a long-term practical difference between these two structures, in that I don’t think one of them necessarily leads to better or more flexible code over time, especially given even rudimentary attention to practical details. But I do think you should be clear about which structure you are using — mixing the two by treating jQuery as a specific dependency of some parts of the code but a general dependency of other parts would probably lead to confusion later on.

Update:

A reddit commenter asked why I wasn’t passing a DOM element into the Widget, as in:

new Widget({parentSelector: document.getElementBy("autodiv")});

My response: I have nothing really against passing in a DOM element beyond it being a little verbose and an old-timey superstition against using getElementBy. Using a DOM element still keeps the dependency in the widget.

Like this? Go ahead and read Master Time and Space With JavaScript

GoogleAnalyticsProxy – now minified

It’s been several years since I released GoogleAnalyticsProxy, which allows our team to test their GA event/click/view tracking during the development phases of our project. Today, I pushed a quick update to it with a minified version of the JavaScript so that there is a smaller footprint.

For more information on how we use it, read my older post, Tracking Google Analytics events in development environment with GoogleAnalyticsProxy.

GoogleAnalyticsProxy – now minified

It’s been several years since I released GoogleAnalyticsProxy, which allows our team to test their GA event/click/view tracking during the development phases of our project. Today, I pushed a quick update to it with a minified version of the JavaScript so that there is a smaller footprint.

<p>For more information on how we use it, read my older post, <a href="http://www.robbyonrails.com/articles/2009/11/01/googleanalyticsproxy-for-development-environment-tracking-events-in-google-analytics">Tracking Google Analytics events in development environment with GoogleAnalyticsProxy</a>.</p><div class="feedflare">