Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

21 August 2008

Function overloading in JavaScript

Trying to write a function so that it will handle different numbers and types of argument always seems to take a lot more code that it should. Today I ended up with some nightmarish if...else... because I wanted to support:

  • Object, Object
  • Object, String
  • Object, Object, String

I remembered a post by John Resig from a while back on this, however his method doesn't handle different types. A quick Google found this snippet which does the job but seems a bit clunky, converting constructors to strings and the like. Satisfied that it could probably be improved upon here is my go at it.

Implementation

Here an Impl class holds the different method implementations against their signatures, defined as an array of constructors. The add method maps a new signature to an implementation, the exec method identifies the correct implementation for the current arguments and executes it and the compile method returns a function that can be used to overwrite the "daddy" function.

function Impl(){
 var _impl = {};
 return {
  add: function(aSignature, fImpl){
   _impl[aSignature] = fImpl;
  },
  exec: function(args, scope){
   var aArgs = Array.prototype.slice.call(args);
   var aCtors = [];
   for(var i in aArgs) aCtors.push(aArgs[i].constructor);
   return (_impl[aCtors] || function(){}).apply(scope, aArgs);
  },
  compile: function(){
   var impl = this;
   return function(){
    return impl.exec(arguments, this);
   };
  }
 };
}

Usage

Here's an example setup of a function stringify that will take two strings, two numbers or an array and do different things depending on what arguments are passed.

function stringify(){
 var someVar = 'Items: ';
 var impl = new Impl();
 
 impl.add([String, String], function(sLeft, sRight){
  return sLeft + ': ' + sRight;
 });
 impl.add([Number, Number], function(iLeft, iRight){
  return 'Sum: ' + (iLeft + iRight).toString();
 });
 impl.add([Array], function(aIn){
  return someVar + aIn.join(', ');
 });
 
 stringify = impl.compile();
 return stringify.apply(this, arguments);
}

Each implementation is added with an array of constructors e.g. [Number, Number] representing the arguments signature to match and the implementation function. Notice that we don't need to do any type checking of the variables in the implementation function, as we have to have matched the signature to get that far, and we can give then relevant names.

Notice the last two lines are:

stringify = impl.compile();
return stringify.apply(this, arguments);

So on the first execution of the function it is overwritten with a "compiled" version and then that version is called on the next line. Subsequent calls to the function will go straight to the "compiled" version thus speeding things up. This could also be done without the compilation and overwriting bit by just calling exec directly thus:

return impl.exec(arguments, this);

Calling our function

stringify('foo', 'bar'); // => 'foo: bar'
stringify(26, 5); // => 'Sum: 31'
stringify( [ 1, 2, 3 ] ); // => 'Items: 1, 2, 3'

Our different numbers and types of argument are giving us the output we'd expect.

16 July 2008

A quick go at CSS preprocessing in JavaScript

Chris Heilmann's post today about CSSPP, a PHP preprocessor for CSS, set the old brain going so I decided to knock up a quick proof of concept (FF only) in JavaScript doing some of the same stuff. Namely, it has very quickly hacked nested rule parsing and a form of the replacement variables feature.

Currently you have to specify your CSS for processing in a script tag with a particular type...


<script type="text/csspp">
.red {
 
 border: 2px solid red;
 
 h2 {
  background: #933;
 }
 
 p {
  background: $derek$;
 }
}
   
.blue {

 border: 2px solid blue;
 background: $other$;
        
}
</script>

...and the variables are retrieved from a JavaScript object by name...


<script type="text/javascript">
var cssVars = {
 derek: '#FCC',
 other: '#CCF'
}
</script>

Obviously a JavaScript implementation like this would slow down the user experience and wouldn't have any of the snazzy caching features of a server-side version but it might be useful if you're hacking a bit of CSS and don't have a PHP server handy.

20 May 2008

dp.SyntaxHighlighter jQuery plugin

I've just added syntax highlighing to the code samples on my blog using the excellent dp.SyntaxHighlighter. Adding a class name e.g. "c#" or "xml" to your pre or textarea elements and calling HighlightAll magically highlights the content and turns the surrounding element into a fancy box complete with toolbar.

I tend to wrap my samples in a <pre><code>...</code></pre> so applying the highlight on the pre tag would have broken because of the additional code inside. A quick gander at the code, bit of refactoring in shCore.js and a jQuery one-liner later and I've got a nice(ish) plugin that will apply highlighting to the elements selected through jQuery thusly:

$(document).ready(function(){
   $("code").syntaxHighlight({showGutter: false, firstLine: 5});
});

The settings are:

  • showGutter < bool >
  • showControls < bool >
  • collapseAll < bool >
  • firstLine < int >
  • showColumns < bool >

You can grab the files from here:

This mod is using the latest stable release (1.5.1) of dp.SyntaxHighlighter. It looks like version 1.6 is in the pipeline with some major changes so I'll keep an eye on that and maybe revisit this when it comes out.

24 April 2008

Cross-browser data binding with jQuery

From version 4.0 Internet Explorer has had the ability to bind certain HTML elements to a client-side data source. Pretty much any data you can access with ADO you can use as a data source but the one we've used most commonly at work is XML. By adding some attributes to your HTML elements e.g.

<input type="text" datasrc="#dsoComposers" datafld="compsr_last"/>

you can get them to render out the data from the data source and, in the case of inputs, persist any changes back to the source. Additionally, if you have a multi-row data source and you bind it to a table the contents of the tbody tag are duplicated for each row.

This is very useful for making web applications because:

  • you only send the raw data along with a small amount of rendering HTML to the client
  • the client edits the data, adding/deleting rows without postbacks
  • the client posts back structured data rather than a ton of awkwardly named querystring variables
  • you need no presentation code for translating your data to or from HTML

All this considered I thought I'd have a go at creating a simple cross-browser version of this databinding functionality in jQuery with a limited feature set.

Features to implement

For this proof of concept I decided the features I would try and implement were:

  • Support for JSON as a data source
  • Repeat rendering of a table's tbody section for each item in an array of objects
  • CSS class name based way of tying properties of the objects to HTML elements
  • Rendering of property values within HTML elements innerHTML or value
  • Attaching of event handlers to persist data changes on inputs back to the array data source
  • Some ability to reflect programmatic changes to the underlying data source in the bound HTML elements
  • Doing the above without needing to fully refresh the HTML every time

Use

Some "template" HTML...

    <table id="info">
      <thead>
        <tr>
          <th>Common name</th>  
          <th>Origin</th>
          <th>First developed</th>
          <th>Use</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="field[name]"></td>
          <td><input type="text" class="field[origin]"/></td>
          <td class="field[developed]"></td>
          <td class="field[use]"></td>
          <td><button class="field[delete]">Delete Row</button></td>
        </tr>
        <tr>
          <td colspan="4" style="border-bottom: 2px solid #888;"><textarea class="field[comments]" style="width: 100%;"></textarea></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="4"><button id="add">Add Item</button></td>
        </tr>
      </tfoot>
    </table>

...some data...

var data = [
   { name: 'Braeburn', origin: 'New Zealand', developed: '1950s, United States', comments: '', use: 'Eating' },
   { name: 'Bramley', origin: 'Southwell, Nottinghamshire, England', developed: 'about 1809', comments: '', use: 'Cooking' },
   { name: 'Cox\'s Orange Pippin', origin: 'Great Britain, New Zealand', developed: 'c. 1829', comments: '', use: 'Eating' },
   { name: 'Empire', origin: 'New York', developed: '1966', comments: 'Lovely white subacid flesh. Tangy taste.', use: 'Eating' },
   { name: 'Granny Smith', origin: 'Australia', developed: '1868, Australia', comments: 'This is the apple once used to represent Apple Records. Also noted as common pie apple.', use: 'Eating or cooking' }
];

...and a small amount of JavaScript...

$(document).ready(function(){
   $('#info').databind(data);
});

The add button handler looks like this...

data.push({ name: '', origin: '', developed: '', comments: '', use: '' });
$('#info').databind(data);

...any code making programmatic changes to the data must recall databind to refresh the bound HTML elements.

Demo

I've set up this quick proof of concept here. I haven't looked at how it performs with large arrays of data but I expect the answer would be badly.

Going forward there may be scope for turning this into a proper jQuery plugin with support for other types of data source and the ability to bind an arbitrary group of elements to some data rather than just a table.

Links

10 December 2007

Reference types in prototype declaration - JavaScript gotcha

I've recently started doing some heavy duty JavaScript, including messing around with constructors, prototypes, lamdas, closures etc. I started off creating a few classes by creating a constructor function and then defining its prototype using object-literal notation as it means your code looks quite like class declarations in other OO languages.

Here is a simple example without any methods, just with two member variables:

function MyClass(){}
MyClass.prototype = {
 iNum: 0,
 sStr: 'Derek'
};

var oA = new MyClass();
var oB = new MyClass();

// oA: iNum -> 0, sStr -> Derek
// oB: iNum -> 0, sStr -> Derek

oA.iNum++;
oA.sStr += ' Fowler';

// oA: iNum -> 1, sStr -> Derek Fowler
// oB: iNum -> 0, sStr -> Derek

All seems well, however, upon adding some reference types to the prototype things get a bit strange:

//...

MyClass.prototype = {
 iNum: 0,
 sStr: 'Derek',
 aAry: []
};

//...

// oA: aAry.length -> 0
// oB: aAry.length -> 0

oA.aAry.push('test');

// oA: aAry.length -> 1
// oB: aAry.length -> 1

Adding an element to aAry of oA has added it to oB's aAry too. "Odd", I thought, so I did a little more investigation:

// MyClass.prototype.aAry.length -> 1

The array property of the instances is pointing back to the property of the prototype. In other OO languages all member variables within the class declaration are copied into the instances, it is only static variables and method implementations that are shared between them. These JavaScript variables seem to be neither member nor static, they are member if value types and static if reference types. Next I tried looping though the properties and testing hasOwnProperty:

for(var sProp in oA){
 // oA.hasOwnProperty(sProp)
}

Before the assignments all the properties return false, that they are not member properties but reside within the prototype. Following the assignment however iNum and sStr return member and only aAry still claims to be prototype.

This behaviour isn't a bug in an implementation either, it is consistant in all the browsers but after having a quick look in the ECMA-262 doc i'm still none the wiser about why this is the case. Anyone who can shed light on this please comment below.

The solution

The solution to this is to create all member variables using the this keyword in the class constructor thus:

function MyClass(){
 this.aAry = [];
}

This ensures that the variable is created upon the new instance and you don't get any sharing problems.