Best practices: Organizing code: Posts

First look: CNET (Redball) Global Javascript Libraries

I’ve been working on a global library for cnet javascript standards and I’ve got my first crack at it ready. I’m going to spend some time in the coming weeks working on documentation and examples, but for those of you interested, here’s a quick look at what’s in the collection. | Read the rest »

Scope in Javascript

via ajaxian (surprise):

Mike West has put some time into analyzing and understanding one of the more sticky issues in Javascript: scope.

Scope is one of the foundational aspects of the JavaScript language, and probably the one I’ve struggled with the most when building complex programs. I can’t count the number of times I’ve lost track of what the this keyword refers to after passing control around from function to function, and I’ve often found myself contorting my code in all sorts of confusing ways, trying to retain some semblance of sanity in my understanding of which variables were accessible where.

He has published his explorations as an article in Digital Web Magazine. In it he deals with the basics of scope; the this keyword in method calls, constructors, function calls and event handlers; the apply() and call() methods; and Prototype’s bind() extension to Function.

The article is illustrated throughout with code examples and includes a list of useful references at the end. A good addition to the family of online Javascript resources.

Objectifying Javascript

I’ve been out of town for two weeks, so I’m just now catching up on all my javascript reading. Here’s the first of what will no doubt be a flurry of posts today.

I found this linked to via ajaxian. It’s a great article on object oriented practices using javascript. A lot of what Jonathan Snook goes over in his article on Objectifying Prototype is taken care of for you using Prototype.js’s Class.create methods and Object.extend methods. I highly recommend reading up on these functions (linked to at the bottom of the article). But this overview is really a great primer for writing class based javascript. | Read the rest »

Prototype Extension: Dynamic Script Pattern Support

Now, what was I just saying?

via Ajaxian:

Cody Swann was working on a web application that was using the Dynamic Script Pattern, which Dojo has excellent support for, but Prototype didn’t.

Cody then extended Prototype to support ScriptSrcTransport similarly to how Dojo does it.

The code below support the Simple, Polling and JSONP and JSON Callbacks described in the Dojo book.

Lazy Loading - Javascript includes on demand

There are several examples of the concept of “lazy loading” out there. Dojo is probably the most well known, but the thing I don’t like about Dojo is that the initial include is so expensive (127K!!! - and that’s before you include any widgets).

While digging through ajaxpatterns.org I found this entry on On-Demand Javascript that outlines the concept really well, illustrates how one would implement it, and also points to a couple of implementatins already out there (including Dojo). It’s worth a quick read, especially as we start considering standardizing some of our code libraries. | Read the rest »

event:Selectors - Behaviour +

I just happened upon event:Selectors. It’s very similar to Behaviour.js (the author’s spelling, not mine) in most respects, though its much smaller (72 lines / ~2k) and has some nice added functionality using Prototype shortcuts (Behaviour is stand-alone and duplicates a lot of Prototype stuff and is, therefore, larger).

Basic usage:

var Rules = {
   '#icons a:mouseover': function(element) {
     var app = element.id;
     new Effect.BlindDown(app + '-content', {queue: 'end', duration: 0.2});
   },

   '#icons a:mouseout': function(element) {
     var app = element.id;
     new Effect.BlindUp(app + '-content', {queue: 'end', duration: 0.2});
   }
 }

Now, this alone is nice, but nothing exceptional. You could do the same thing with prototype thusly:

Event.observe(window,"load",function() {
  $$('#icons a').each(function(tag) {
    Event.observe(tag,'mouseover', function() {
      var app = tag.id;
      new Effect....
    });
  });
});

Ok, so it’s definitely longer to do without it, but not terribly so. But what really gets me excited is this:

 '#footer:loaded': function(element) {
    element.setStyle({backgroundColor: '#ccc'});
  }

This will apply the code to the element once it’s loaded. That’s just awesome. That’s just awesome times five. Wait, it gets better: it will also apply all your rules to your Ajax responses, too (if you want it to). This means when you bring in a chunk of html into the DOM you don’t have to set up all your events on it again.

It has a few other nice touches (you can, for instance, apply these events to more than one selector, for instance). Check it out.

Prototype Tutorial followup: Enumerable and Hash

At the bottom of the prototype tutorial I just posted is this great article on Encytemedia.com that digs into the Enumerable and Hash functions of the library in greater detail. There’s a lot of great stuff in here.

each and friends

I used to find myself writing a lot of for loops. Although, Prototype doesn’t by any means eliminate the need to do for loops, it does give you access to what I consider to be a cleaner, easier to read method in each.

for(var i = 0; i < F.Numbers.length; i++) {
  logger.info(F.Numbers[i]);
}

each allows us to iterate over these objects Ruby style.

F.Numbers.each(function(num) {
  logger.info(num);
});

//Output
0
1
4
5
98
32
12
9

each takes one argument, the iterator or block in Ruby terms. This iterator is invoked once for every item in the array, and that item along with the optional index is passed to the iterator. So if we also needed the index we could do something like the code below.

F.Numbers.each(function(num, index) {
  logger.info(index + ": " + num);
});

//Output
0: 0
1: 1
2: 4
3: 5
4: 98
5: 32
6: 12
7: 9

window.onload and its issues

Bill Graham was asking me about where to put javascript events today. window.onload? At the bottom of the html document? Attached to the onload event of an image somewhere in the page?

Here’s an article by Dean Edwards on an interesting solution that works for IE and Firefox.

For the life of me, I can’t find the article that I read a week or so ago on this topic that outlined numerous strategies on dealing with window.onload issues, but one option to consider is using event monitoring in prototype to monitor the browser for an element to be present before performing an action on it.

Show Love to the Object Literal

Another snippet via Ajaxian:

A Javascript tip from Chris Heilmann, who reckons the object literal is “pretty close to sliced bread”. Replace:

var commonSense=null;
var standardsCompliance=“50%”;
function init(){
// code
}
function doStuff(){
// code
}
function doMoreStuff(){
// code
}

with the object literal form:

awesome={
commonSense:null,
standardsCompliance:“50%”,
init:function(){
// code
},
doStuff:function(){
// code
},
doMoreStuff:function(){
// code
}
}

| Read the rest »

Javascript Namespace Solutions

In the past two weeks, I have run into live site issues due to namespace problems (javascript functions being named the same) in our javascript files.

I came across this article about versioning. It mentions some solutions for this problem.
| Read the rest »

Categories

Archives

Links and whatnot