Archive

Archive for the ‘JavaScript’ Category

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 , , ,

Flot: What’s the point!?

March 20th, 2008

Here’s a screen shot:

flot-example.png

What the hell is the point.  You can do this in flash and have more interactive graphs.  Granted it’s pretty, but so would any custom flash chart, or if you’re not the custom kind, there’s Open Flash Chart.

Seriously people.  jQuery is great for making the client side more interactive, but Flash has JavaScript graphics rendering beat.  It’s faster.  Faster to render and faster in response time.

Don’t even play the “Flash may not be installed card” because I’ll turn around and use my “JavaScript may not be enabled” one.  Every person online today can see youtube videos and so has flash enabled and the web is useless unless you have JavaScript enabled.  So these are not really valid arguments.

Rant complete,

Allain

JavaScript, User Interfaces

Securing JavaScript Applications

November 12th, 2007

One big problem with using JavaScript as the basis for your application is that if a hacker gets clever they can insert their own JavaScript into your trusted page and execute it as though it were yours (XSS).

You could curtail a hacker by modifying the DOM so that the objects they would typically use to perform the hack have been replaced, or modified, so that they are lame. This wouldn’t hurt your code since, if well written, it would save references to the the unchanged objects.

For example you could:

  • define an empty function called XmlHttpRequest
  • crawl the DOM and remove, or replace, appendChild and other DOM methods making Dynamic script tags impossible to insert.
  • _document = document; document = {}; // Making it more difficult to get your hands on the document object

I haven’t heard anyone talk about this before so I’d love to hear what people think.

Thanks,
Allain

JavaScript, Security

Online Graph Editor

October 5th, 2007

I got this working today I’d share it.

It’s definitely a work in progress, but I figured I’d get it out there so that it could illicit some feedback.

Until I can sit down infront of a windows box to fix it, it only works in firebox and chrome.

http://graph.machete.ca/

JavaScript, PHP, Programming

Machete Mice

October 3rd, 2007

An alternate user interface for a plain old Chat System.

http://mice.machete.ca

JavaScript, PHP, Programming, User Interfaces

TheBrain Clone

October 2nd, 2007

I’ve coded this website to demonstrate that web interaction need not be boring. It’s based on “TheBrain” which when I wrote this page was only a desktop application.

http://www.machete.ca/slips/

JavaScript, Programming, User Interfaces

Fisheye Calendar

September 28th, 2007

As yet another proof of concept I’ve implemented a **zooming calendar system**.

It’s an attempt to retain user context even when drilling down into the details of an arbitrary interface. Calendar just happens to be a slick demo.

Thoughts?

http://calendar.machete.ca/test/2007/11/

JavaScript, PHP, Programming, User Interfaces ,

Modeless Webpage Editor

September 27th, 2007

Here’s my prototype for a modeless website WYSIWYG.

http://www.machete.ca/mui/

It doesn’t persist, it doesn’t have many commands, and it’s not exactly pretty. But what it does have is something I haven’t seen online before.

I’m hoping to turn it into a “muscle memory editor”. This is so beyond thought through that I’m not even sure if it’s useful, but it is neat.

Hope someone finds it interesting.

Allain

JavaScript, Programming, User Interfaces