Archive

Posts Tagged ‘JavaScript’

JavaScript Mock Objects

December 23rd, 2009

While testing a library I’m writing I found that I needed to pass in a simple mock object with a small set of methods and track how many times and with what values each of the methods gets called.

The following snippet of code is what I came up with.

function mock() {
    var mockMethods = arguments;
 
    var dummy = {}
    dummy.calls = [];
 
    for (var i=0; i< mockMethods.length; i++) {
        var methodName = mockMethods[i];
        dummy.calls[methodName] = [];
        dummy[methodName] = (function(methodName) {
            return function() {
                //Convert function arguments into an array
                var args = [];
                for (var i=0; i<arguments.length; i++) 
                    args[i] = arguments[i];
 
                this.calls[methodName].push(args);               
            }
        })(methodName);
    }
 
     return dummy;
}

And in an qunit test I’d use it like this:

test("fills rect when bounds and fillStyle are good", function() {
    var n = new PNode({
        bounds: new PBounds(0, 0, 20, 20),
        fillStyle: "rgb(255,0,0)"
    });
 
    var mockCtx = mock("fillRect");
    n.paint(mockCtx);
 
    same(mockCtx.calls.fillRect[0], [0,0,20,20]);
})

I hope someone finds this useful.

Agile Development, JavaScript , , ,

Google Analytics Trick

December 22nd, 2009

It’s not much, but the following jQuery trick allows me to track all outbound links on the site without modifying each and everyone of them.

try {
  var pageTracker = _gat._getTracker(TRACKER_CODE_HERE);
  pageTracker._trackPageview();
 
  $(function() {
    $("a").click(function() {
      var href = this.href;
      if (href.toString().indexOf("SITE_DOMAIN_HERE") == -1) {
        pageTracker._trackPageview('/outgoing/'+href.substring(7));
      }      
    });
  })
} catch(err) {
}

JavaScript , ,

Client-Side JavaScript DSLs

December 14th, 2009

This blog post is about solving one of my JavaScript paint points; specifically its verbosity when defining inline functions. The way in which I solve it is interesting to me and hopefully to someone else too.

Here goes…

Why not do DSLs on the client side by compiling to JavaScript in a compiler written in JavaScript?

I realize that doing a “true compiler” is computationally expensive, but the leaps in JavaScript performance we’ve seen lately make it tractable.

To do the job with the respect it deserves, you need to build a full parse tree, but for my particular DSL, a replacement scheme that relies on regular expressions should do fine except in the pathological cases. Except for obfuscated code, I have yet to find a piece of code that uses commas to separate expressions for example.

So, what do I have in mind?

I love the JavaScript language, but its format for defining lambda expressions is nasty. You’re forced to insert the function keyword where (except for pathological cases) it could be inferred from its context. This wouldn’t bother me at all if I wasn’t required to define them so often while working with jQuery.

For those who are visual, this is the code I’d like to write:

<script type="text/x-javascript">
$({ 
  alert("Hello"); 
 
  $("a").click((e) { 
    alert("clicked"); 
  });
 
  $.post("testing.php", {a: 100, b:100}, (result) { 
    alert("Result is: " + result);
  });
});
</script>

And this is the code I have to write right now:

<script type="text/javascript">
$(function() { 
  alert("Hello"); 
 
  $("a").click(function (e) { 
    alert("clicked"); 
  });
 
  $.post("testing.php", {a: 100, b:100}, function(result) { 
    alert("Result is: " + result);
  });
});
</script>

Now, it’s not a big change, but it’s definitely worth it as your jQuery lambda heavy code starts to balloon.

This is how you could make it happen:

  1. Define a script section that uses an “invalid” mime type and place your code there. This will be ignored by the browser, so you won’t get any syntax errors.
  2. Include an external script that searches for scripts of a certain type, converts them, then evaluates.

If you want to see this idea in action take a look here: http://www.machete.ca/x-javascript.html

I can’t be the first person to have thought of this, but I thought I’d tell it on the mountain just incase.

Thoughts?

Ideas, JavaScript, Programming , , ,