Archive for July, 2010

* BlackBerry JavaScript Oddities

Posted on July 18th, 2010 by Dave Johnson. Filed under Uncategorized.


I have just discovered that the Element object in the BlackBerry browser (4.6+) supports the prototype object on some objects but not others. In particular the Element object supports it like this:

1
2
3
Element.prototype.addEventListener = function() {
    alert('foo');
};

but the following does not work on the Document object:

1
2
3
Document.prototype.addEventListener = function() {
    alert('bar');
};

What does work on the Document is overriding instance method like this:

1
2
3
document.addEventListener = function() {
    alert('foobar');
};

Strange but true!

If you have any other BlackBerry tidbits please let me know since these old versions of BlackBerry browser are going to be the IE6 of the the mobile web.

.



* JavaScript Event Merging

Posted on July 14th, 2010 by Dave Johnson. Filed under JavaScript.


In a recent project I finally decided to write something to help with JavaScript event merging. There are often cases in JavaScript where you want some code to run but only after certain events have fired or other code run - in my case I wanted to execute a JavaScript function only after two different bits of code had executed. The most common use case for event merging I have come across has got to be on page load / DOM ready where you may need several conditions to be true before executing some JavaScript code.

Event merging generally helps you to better separate your concerns and not have unwieldy if conditions strewn throughout your code checking if certain condi.

If you have a basic JavaScript object called the “Subject” that has subscribe, subscribeOnce (events that auto-unsubscribe themselves after being fired the first time), and notify methods on them. You can use the following merge function to have all subscribed code executed only after each of the events passed to the merge function are fired. In this case I have explicitly used the subscribeOnce method on the event.

1
2
3
4
5
6
7
8
9
10
11
function merge(handler, events) {
       var i = events.length;
       var f = function() {
           if (!(--i)) handler();
       }
       for (var j=0; j<i; j++) {
           var e = events[j];
           (!e.fired?e.subscribeOnce(f):i--);
       }
       if (!i) handler();
}

When the merge function is called it iterates over all the events in the event array argument and checks if that event has already been fired or not by checking the “fired” property on the event - note that this makes it so that it doesn’t matter if merge is called before or after the events have fired. If the event has not been fired yet then a handler is attached using subscribeOnce where the handler checks a counter indicating how many of the events have been fired, once the counter hits 0 then the final handler for the merged events is called.

I have put up an entire event merging code on Github here.

Tags: .