ciplogic.com
Live with grace. Write superb software.

javascript

  • A better event system (for JavaScript)

    I've seen a lot of APIs that have the bad habbit of having the event types described as String. jQuery (JavaScript) and SWT (Java) are two popular examples that allow extensions of the event system using String names. Generally the API is composed by 2 methods:

    1. the Add Listener method: on / addPropertyChangeListener
    2. the Fire Event method: fire / notifyPropertyChange

    While the naming conventions are different, in spirit they do the same thing. The problem with this approach that if you do instead of:

    1
    element.on("click", function() { ... });

    this

    1
    element.on("clickl", function() { ... }); // invalid event type

    you won't even notice it unless many hours of pointless debugging have passed.

    So I believe that JavaScript APIs (in particular) should go in a different direction, where you could see the problem the moment you try to listen to an event that does not exist, by throwing an exception on the Add Listener method. Thus, another method would be needed to actually register the event type to the specific element, so we will have:

    1. the Register Event method: event / addEvent (?)
    2. the Add Listener method: on / addPropertyChangeListener. Note that this will now throw an exception if an invalid listener will be registered.
    3. the Fire Event method: fire / notifyPropertyChange. This now can also throw an exception if the event was not registered.

    Since we're developers here, some API calls would look like:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    var element = $("#whatever");
     
    // wrong
    element.on("customevent", function() {...}); // throws exception
     
    // good
    element.event("customevent"); //now only we can register listeners to it.
    // later ...
    element.on("customevent", function() {...}); // works just fine.

    Note, that it doesn't mean this should be the final API. Personally I think the best looking API is something along the way that after the registration, you could call the API only via members of the on object. Something like this:

    1
    2
    3
    element.on.customevent.addListener(function() {...});
    element.on.customevent.removeListener(func);
    element.on.customevent.notify(eventData); // trigger the actual event

    But I am convinced that the actual event types should be tied to the object that can generate them.

    Advantages

    In my opinion this approach has these advantages:

    • Faster time from the error introduced in the code, to the error report. (we won't generate non existing events, nor listen to non existing ones).
    • The possibility of interrogating an object on what events it can raise at runtime.

    The only drawback I can think of, is that you can't listen to events before they are registered, but I haven't yet seen any real life application where this actually happens.

  • core-lang: Better Collection Classes for JavaScript

    It brings me great joy to announce the release of version 1.0.0 of core-lang, the collection classes I wrote for JavaScript.

    Overview

    With an API that is fully compatible with the JavaScript API, keeping the same signatures and behaviors for functions such as forEach, etc, but also inspired from groovy, having methods such as groupBy, chaining support, and full Promise support, allowing to deal with collections that contain promises, or are transformed to promises, using simple chainable calls.

  • core-promise and core-lang Promise ES6 TypeScript API updates

    core-promise

    After a bit of fiddling around I managed to convince the core-promise implementation to actually implement the Promise interface from the ES6 typescript definitions itself:

    /**
     * Represents the completion of an asynchronous operation
     */
    interface Promise<T> {
        /**
        * Attaches callbacks for the resolution and/or rejection of the Promise.
        * @param onfulfilled The callback to execute when the Promise is resolved.
        * @param onrejected The callback to execute when the Promise is rejected.
        * @returns A Promise for the completion of which ever callback is executed.
        */
        then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => TResult | PromiseLike<TResult>)" Promise<TResult>;
        then<TResult>(onfulfilled?: (value: T) => TResult | PromiseLike<TResult>, onrejected?: (reason: any) => void): Promise<TResult>; 
        /**
         * Attaches a callback for only the rejection of the Promise.
         * @param onrejected The callback to execute when the Promise is rejected.
         * @returns A Promise for the completion of the callback.
         */
        catch(onrejected?: (reason: any) => T | PromiseLike<T>): Promise<T>;
        catch(onrejected?: (reason: any) => void): Promise<T>;
        [Symbol.toStringTag]: string;
    }

    Thus not only you have now all the test guarantees, you also get the API guarantees. Neat!

  • fast-live-reload 2.6.0 Can Run Commands for Each File

    If you don't know what fast-live-reload is you should probably see this video. TL;DW: unlike any other live reload tool on the planet, fast-live-reload can build execution pipelines (probably the only one still from the command line), serve folders, proxy sites, etc. Truly a Swiss army knife.

    More than once when monitoring folders, I wanted to execute commands for the specific files that would change.

    A good example that comes to my mind is AsciiDoc. When I monitor a folder where I have a bunch of asciidoc files, I want to run asciidoctor individually. For that file. So far that was not really possible. What I would do would be, decide upfront on what file I would work, and run:

    fast-live-reload -o '*.adoc' -e 'asciidoctor mycurrentfile.adoc'

    "Superb", I know.

    Finally, since version 2.6.0, if in the executed command the variable $FILE is defined, the command will be executed for each changed file, and the FILE environment variable will be passed to the script. Thus the previous example would be:

    fast-live-reload -o '*.adoc' -e 'asciidoctor $FILE'

    Yay!

    If you want this tool, you need node and just:

    npm install -g fast-live-reload

     

  • fast-live-reload Presentation

    When creating web applications, a lot of time is consumed switching back and forth between the code and the application itself. What if there would be an application that would refresh your browsers automatically?

  • Good Code Exists

    A PHP programmer was begging on a street corner. With dirty clothing, extremely sad and distracted, was watching the ground. On the cardboard in front of him was written: "Help a poor PHP programmer".

    From time to time, a Java or C# developer would give him something.

    A Python programmer that happened to pass by, stopped, took the cardboard, wrote a few words, then left.

    Something amazing happened. Ruby, Groovy, C# and Java programmers were stopping, reading what was written and giving plenty of money, some of them with tears in their eyes, crying with deep sorrow. A pretty large crowd gathered around him, so the PHP programmer raised his eyes. He read the cardboard, and cried with a shriek from the bottom of his lungs, lungs of a despaired man, from his truly unfortunate state. Tears started flowing over his cheeks, faced now with the truth revealed to his soul, when he read the words:

    "Help a poor PHP programmer. I know good code exists, I just have never seen it."

    A Perl programmer, extremely dirty, with his ripped clothing, and disheveled hair also passed trough the crowd, bumping into people. Unfortunately no one discovered the meaning of the senseless words he was muttering, so they let him be, to continue his painful existence.

  • Inspecting CSS Using IE8 Development Tools

    WHY!? How?!, I don't even...

  • JavaScript Debugging 1 : A small utility function

    In this small series, I'm going to start explaining how to do JavaScript debugging, namely bug tracing at the advanced level, since I can't seem to find tutorials except how to actually run the debugger itself.

    So in order to start, let's build first an utility class that we'll use in several places, the onceMany utility function:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    (function() {
     
    if (!window.ciplogic) {
        ciplogic = {};
    }
     
    ciplogic.onceMany = function(once, many) {
        var firstGenerated = false;
        return {
            next : function() {
                if (firstGenerated) {
                    return many;
                } else {
                    firstGenerated = true;
                    return once;
                }
            }
        }
    };
     
    })();

    As you can see at line 3, we will keep everything in the ciplogic namespace. From this moment on, we can call:

    1
    2
    3
    4
    5
    6
    var comma = ciplogic.onceMany("", ", "),
        result = "";
     
    for (var i = 0; i < arguments.length; i++) {
        result += comma.next() + parseArgument(arguments[i]);
    }

    And we don't need to keep a new array for join operations.

     

  • JavaScript Exception Error Logging Pattern

    Many times in JavaScript, I like to log errors in case exceptions happen, that output what exactly went wrong, without actually taking action.

    For example:

    1
    2
    3
    4
    5
    6
    try {
      callPotentialDangerousStuff();
    } catch (e) {
      console.error("dangerous stuff is not working :(");
      throw e;
    }

    This has the side effect of loosing the stack trace if I break on "uncaught exceptions", and breaking on "all exceptions" is absolutely no option, since many frameworks use the exception handling as mechanisms of detecting various features of the browser environment.

    Thus I came up with this pattern:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var executionSuccessful = false;
     
    try {
      callPotentialDangerousStuff();
      executionSuccessful = true;
    } finally {
      if (!executionSuccessful) {
        console.error("dangerous stuff is not working :(");
      }
    }

    So if an exception happens, I can still break on all exceptions, but also get my log right.

    Can you imagine how cool it would be to chain exceptions like in Java? For example:

    1
    2
    3
    4
    5
    6
    try {
      callPotentialDangerousStuff();
    } catch (e) {
      console.error("dangerous stuff is not working :(");
      throw new Error("dangerous stuff", e);
    }

    At least we can dream about it, and appreciate more languages that do offer chaining of exceptions.

  • JavaScript Exception Handling HowTo

    A very used paradigm when it come with dealing with errors is the try/catch construct.

    In JavaScript you can throw anything as an exception, and in your catch statement you will receive that object instance that you threw. This is pretty cool, because when you receive the catched object, it might contain valuable information on what actually went wrong. In most cases though people just pass a string with the error message.

    I've seen advanced programmers actually throwing the message itself as the thrown object, in code that I will simplify as this:

    1
    2
    3
    4
    5
    6
    7
    try {
        console.log("computer reports heating at engine 1.");
        throw "oh man, catastrophic failure at engine 1.";
    } catch (e) {
        console.log("last words were:", e);
        console.log('the time backtrack saving device took note of the missing ship.');
    }

    Output:

    1
    2
    3
    computer reports heating at engine 1.
    last words were: oh man, catastrophic failure at engine 1.
    the time backtrack saving device took note of the missing ship.

    Unfortunately this is a problem, since we got the error message, and it looks good in our 7 lines of code. In reality if our program was a bit bigger, our message was now meaningless, since we would need to find from where the thing was thrown. If the code that can cause the catastrophic failure is called from multiple sites, this only adds to the complexity.

    This is why you always use the Exception object. The Exception object is part of standard JavaScript, and in all browsers,Chrome, Firefox, and IE from version 10 onwards (no one uses IE9 on their space ship anyway) has an extra property, named stack, that gives you the stack trace:

    1
    2
    3
    4
    5
    6
    7
    8
    try {
        console.log("computer reports heating at engine 1.");
        throw new Error("oh man, catastrophic failure at engine 1.");
    } catch (e) {
        console.log(e.stack);
        console.error("the pilot warning message was:", e);
        console.log('the time backtrack saving device went back in time and send a bot to fix the engine.');
    }

    This gives the output:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    computer reports heating at engine 1.
    Error: oh man, catastrophic failure at engine 1.
       at window.onload (http://fiddle.jshell.net/_display/:26:5)
    the pilot warning message was: Error: oh man, catastrophic failure at engine 1.
       "the pilot warning message was:"
       {
          [functions]: ,
          description: "oh man, catastrophic failure at engine 1.",
          message: "oh man, catastrophic failure at engine 1.",
          name: "Error",
          stack: "Error: oh man, catastrophic failure at engine 1.
       at window.onload (http://fiddle.jshell.net/_display/:26:5)"
       }
       
    the time backtrack saving device went back in time and send a bot to fix the engine.

    So please always use Exception objects and avoid space ship tragedies.

  • Joomla Fast Performance With Responsive Templates

    When creating websites performance is one of the main concerns that must be addressed. Fortunately with tools such as Google Page Speed measuring performance, with concrete actual improvement steps that can be taken. So when I've seen that the performance of this website was in the gutter, I know I had to take concrete actions:

    1. Compression

    The first quick win for a site is to activate compression.

  • JsDoc: Holy Mother of Evolution

    So here I was, minding my own business, and trying to write some JavaScript documentation, when IDEA tells me in their very thin documentation, that they support JsDoc.

    Good, let's see it:

    Sourceforge? Was it written by dinosaurs? I remember dinosaurs used to use Sourceforge and put their stuff there. T-Rexes typing with their tiny hands, were the main committers using it, but since poor T-Rexes went away, no one replaced them. Come back T-Rex. We miss you.

    Fine let's see the Rhino-based JSDoc.

    Notice the vibrant community of 2 committers, and yet starred by 841.

    And then finally:

    Wow!!

     

    Let those numbers sink in: 51 contributors, last commit 17 hours ago, 2593 people starred it.

     

    Wow!

    You can literally feel the history of this project, and the fantastic boom that had it now, which tell you in turn what happened with JavaScript since 2010 till now.

     

    And still has Rhino support in case you missed it from v2. Completely unrelated quote:

    Let it go! Let it go!

    Elsa (Frozen)

    I'm not sure of the context where she said these. Might have been unrelated to JavaScript, and in relation to some past history and ice and snow of hers.

  • Live reloading web pages using VIM

    Do you want to live reload the browser as you edit and save using VIM?

    Well wait no more, you can install the application by simply running:

    1
    2
    npm install -g fast-live-reload
    fast-live-reload

    Afterwards whenever saving, the page is automatically reloaded. Without any browser plugins.

    fast-live-reload in action

  • Native vs Bluebird vs Core-Promise Benchmark

    I just took for a test the native promises implementation (that is available since node v0.12), the bluebird implementation, and core-promise, my own TypeScript implementation.

    The tests are here for the native, bluebirdor core-promise. Note that all the implementations pass the full Promises/A+ test spectrum of 872 tests.

    I ran each test file 11 times, using:

    1
    for f in `seq 0 10`; do time mocha test-core-promise.js > /dev/null 2>&1; done

    Obviously, I changed the file name between iterations.

    I removed 11.9 seconds, because these are setTimeouts in the actual tests, remaining with actual execution of promises time, and these are the final results (in seconds):

     

    Native Bluebird Core-Promise

    1.616 1.760 1.564

    1.567 1.626 1.520

    1.568 1.669 1.548

    1.539 1.657 1.573

    1.574 1.595 1.557

    1.583 1.604 1.580

    1.543 1.582 1.540

    1.529 1.622 1.567

    1.600 1.605 1.567

    1.407 1.661 1.544

    1.467 1.640 1.587

     

    Conclusion

    Unsurprisingly the native implementation won performance wise, but only less than 1% compared to the core-promise, but ~5% compared to bluebird. Also core-promise defaults to the native promises implementation if it's available, if you would use the exported Promise class (for tests I accessed the CorePromise implementation on purpose).

    1
    var Promise = require("core-promise").Promise;

    Not to mention readability of code: core-promise's Promise vs bluebird's Promise.

    *Disclaimer* I am the creator of the core-promise, and yes I feel pretty good getting better performance than the "unmatched performance" of bluebird. :)

  • o=o YUI3 is Watching You

    Do you know why you would name a configuration object „o”?

    Because then you can write this:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
        /**
        Applies a new configuration object to the config of this YUI instance. This
        will merge new group/module definitions, and will also update the loader
        cache if necessary. Updating `Y.config` directly will not update the cache.
     
        @method applyConfig
        @param {Object} o the configuration object.
        @since 3.2.0
        **/
        applyConfig: function(o) {
     
            o = o || NOOP;
     
            var attr,
                name,
                // detail,
                config = this.config,

    Personally I would have preferred:

    1
        o= !o ?NOOP :o ; // note how many emotions are bundled in this code.

    But it looks amazing anyway, that o=o is looking straight into my developer soul.

    From here: https://github.com/yui/yui3/blob/master/src/yui/js/yui.js 

    PS: Why else would someone name an object variable "o"?

  • Problems With JavaScript Worker Threads

    I recently just updated a library to handle worker threads under GWT, and I got to learn a bit more about the unique design of worker threads from javascript.

    Here is a quick overview, in case you don't know much about them:

    1. There is no locking in javascript, so worker threads start asynchronously, and the only way to communicate with them is via the postMessage/onmessage API. There is no join(), wait(), synchronized blocks, or other sane threading paradigm you grew used to.
    2. There is no shared state, so every single message is transparently serialized back and forth. Did your thread processed 100MB of data? Well let me serialize that for you to get it on the other thread. Is there some global structure you want to work on parallel with multiple threads - like an image for example? Forget about it.
    3. There is no shared code, so worker threads must be created with their source independently - as a constructor argument. Packaging must be done basically separately for your "thread".

    Let me translate this for you: Worker threads are a pain to even package in their own files, you can't call something like:

    1
    2
    3
    new Worker(function() { // this would be the worker instance.
        this.postMessage("send data back to parent");
    });

    No, that would be too easy, since from that method I could be able to access shared state, so let's make it awkward and weird, why not:

    1
    new Worker("my-worker.js");

    and from the new file call:

    1
    self.postMessage("send message back to parent");

    All the libraries, that you use both in your worker, or in your main code? Better load them twice.

    But wait, there's more!

    The window and document objects are not visible(that would be shared state, invalidating the fabric of JavaScript itself), so adding new scripts can be done via the importScripts function, but that's only if you are from inside a worker. importScripts for the window context? You must be talking the crazy talk. So you get a different approach even in loading external scripts from the different context window/worker.

    There is a new object visible named self, that is the worker reference (if it's a script inside a window, self == window). 

    So let's say you would want to process async a bunch of data, whenever it's being sent from the parent - again, there is no shared context, well why not go with:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    function doActualProcessing() {
      //...
    }
     
    self.onmessage = function(ev) {
      // could be long running
      var result = doActualProcessing(ev.data); 
      
      // I hope for your sake, result isn't big in size.
      self.postMessage(result);  
    }

    Looks simple, isn't it? Except it's in a different bloody file, and did I mentioned that breakpoints in the worker thread code don't stop?

    Fascinating.

  • Simple tracing of JavaScript.

    Have you ever tried to debug javascript that works on focus/blur events? The moment the breakpoint stops on your onFocus method, suddenly the blur event is thrown because hey, the debugger is now focused, and not your element.

    And it's not only that, timer events, and others are really tricky to debug, and you would generally just want to trace expressions, preferrably without changing the underlying code.

    How can you then create trace calls, to see various variable states?

    Well it's relatively simple, we will add tracer breakpoints:

    1
    2
    3
    4
    5
    6
    function log(what) {
        var currentTime = new Date().toString().replace(/.*(\d\d:\d\d:\d\d).*/, "$1");
        console.log(currentTime + " " + what);
     
        return false;
    }

    First we will simple evaluate the previous function in the web console of your favourite browser.

    Now we can simply add a conditional breakpoint, with a condition such as:

    log("X is: " + node.getX())

    Since the breakpoint is evaluated in the context of the current stack, variables such as node will be accessible, if they are present in the code.

    Also, since the function always returns false, the debugger won't stop there, thus no blur/focus events will be triggered.

    If you also need a conditional breakpoint exactly at the line where the log is you can use as expression something along these lines:

    log("X is: " + node.getX()) || !!(actualJsCheck)

    Thus the log will take place, and since it's false, it will fallback in evaluating the actual value that you want the debugger to stop.

    Pretty awesome.

    Have fun debugging.

  • Stop Doing Double Negations

    Did your mind needs to stop to read (taken from ckeditor source):

    1
    2
    if ( !dontRemove )
        removeNoAttribsElement( element );

    Well you're not alone.

    Stop using double negations, even if your code looks "cleaner", and refactor them to be single negations.

    A simpler rule is never use negation variable names, so you don't run into issues like this. So don't use names such as: "noElementPresent", "dontRemove" or "notExisting".

    For the previous example instead of "don't remove" go with "keep element", "keep", or something along those lines. Just search a thesaurus if you can't find a word.

    1
    2
    if ( !keepElement )
        removeNoAttribsElement( element );

    Notice how readability is just so much better.

  • Sweet-Sweet JavaScript Debugging

    Who said dynamic languages can't be fun to debug?

  • TypeScript unit testing with Mocha

    I am writing some unit tests for my TypeScript collection classes (actually migrating some older tests), and I decided in going with Mocha.

    How easy it is? Well, as simple as 1, 2, 3... 4 :) :

    1. Install the typing files

    tsd install mocha
    tsd install node
    tsd install assert

    2. Write your test(s)

    For this example, I'm presenting you a super simple test, but obviously nothing stops you from adding new ones (check my github core-lang project for details):

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    /// <reference path="../../../typings/mocha/mocha.d.ts"/>
    /// <reference path="../../../typings/node/node.d.ts"/>
    /// <reference path="../../../typings/assert/assert.d.ts"/>
     
    import { list, XIterable, XIterator } from "../../main/core/Iterable";
    import assert = require("assert");
     
    describe('ArrayList', function() {
        it('should allow filtering', function() {
            var items : XIterable<number> = list([1, 2, 3, 4]),
                filteredItems: XIterable<number>,
                iterator : XIterator<number>;
     
            filteredItems = items.filter(it => it % 2 == 0);
            iterator = filteredItems.iterator();
            
            assert.equal(iterator.next(), 2);
            assert.equal(iterator.next(), 4);
            assert.notEqual(iterator.hasNext(), true);
        });
    });

    3. Build your test(s)

    I use Grunt, so I have (I deleted all the non test stuff), but is basically easy to see the target that is named "test" across all the plugins in the original full Grunt file:

Germanium

The one to rule them all. The browsers that is.

SharpKnight

SharpKnight is an Android chess game.

MagicGroup

MagicGroup is an eclipse plugin.