Fork me on Github s

Posts Tagged javascript

Javascript Syntax Highlighter

I just want to do a quick shout out to Alex Gorbatchev for his most excellent Javascript syntax highlighter.  I installed it to the blog and am very happy about it.  You can now hover over code snippets and copy+paste, view, or print the code.

So, if you have a blog or other use for it, I highly recommend it.

Tags:

No Comments

Extending Currying: Partial Functions in Javascript

Last week I posted about function currying in javascript.  This week I am taking it a step further by adding the ability to call partial functions.

Suppose we have a graphing application that will pull data via Ajax and perform some calculation to update a graph.  Using a method with the signature ‘updateGraph(id,value)’.

To do this, we have do something like this:


for(var i=0; i < things.length; i++) {
  Ajax.request('/some/data', {id: things[i].id}, function(json) {
    updateGraph(json.id, json.value);
  });
}

This works fine.  But, using this method we need to return the id in the json response from the server.  This works fine, but is not that elegant and increase network traffic.

Using partial function currying we can bind the id parameter and add the second parameter later (when returning from the asynchronous call).  To do this, we will need the updated curry method.  I have added support for sending additional parameters at runtime for curried methods.

Function.prototype.curry = function(scope) {
  scope = scope || window;
  var args = [];
  for (var i=1, len = arguments.length; i < len; ++i) {
    args.push(arguments[i]);
  }
  var m = this;
  return function() {
    for (var i=0, len = arguments.length; i < len; ++i) {
      args.push(arguments[i]);
    }
    return m.apply(scope, args);
  };
}

As you can see, partial currying gives is a very useful tool and this simple method should be a part of every developer’s toolbox.

Tags:

No Comments

Function currying in Javascript

Do you catch yourself doing something like this often?


  Ajax.request('/my/url', {'myParam': paramVal}, function() { 
    myCallback(paramVal); 
  });

Creating a function which calls another function asynchronously is a bad idea because the value of paramVal may change before it is called.  Enter the curry function:


Function.prototype.curry = function(scope) {
  var args = [];
  for (var i=1, len = arguments.length; i < len; ++i) {
    args.push(arguments[i]);
  }
  var m = this;
  return function() {
    m.apply(scope, args);
  };
}

This function creates a wrapper around the function and ‘locks in’ the method parameters.  The first parameter is the scope of the function call (usually this or window).  Any remaining parameters will be passed to the method call.  Using the curry method the above call changes to:


Ajax.request('/my/url', {'myParam': paramVal}, myCallback.curry(window, paramVal));

Remember when passing objects to the curry method that the objects members may still change.

Tags: ,

2 Comments

Disable Select Options in Internet Explorer 7 with JQuery

I recently found out (unfortunately) that disabling an option with the disabled attribute does not work in IE 7.  Odd.  Here is my workaround using JQuery, it will gray out and disallow selection of all options with a disabled attribute.

   $(document).ready(function() {
     $('option[disabled]').css({'color': '#cccccc'});
     $('select').change(function() {
       if(this.options[this.selectedIndex].disabled) {
         if(this.options.length == 0) {
           this.selectedIndex = -1;
         } else {
           this.selectedIndex--;
         }
         $(this).trigger('change');
       }
     });
     $('select').each(function(it) {
       if(this.options[this.selectedIndex].disabled)
         this.onchange();
     });
   });     

Tags: , , ,

8 Comments

Gracefully degrading AJAX calls

What happens if grandma fires up her Packard Bell and attempts to buy some medicinal ointment from your site in IE 5?  Or, what if one of your 3rd party advertisers (likely story) causes a javascript error?  Will your page still work?  Have you ever thought of what happens when javascript is not running on your fancy AJAX pages?

Not many of us do.  But, it is still important to think about what will happen if javascript is not running in the user’s browser.  Around 5% of user’s have javascript completely turned off.  Still other’s may have security settings which disallow ajax calls or obsolete browser’s which are not supported.  Degrading your javascript gracefully can be tedious and time consuming.   However, if you follow the pattern that I present it is hardly an inconvenience at all.

Consider the following code:

   
   

Pretty simple.  We can see that when the link is clicked an ajax call is made.  The click event returns false, preventing the browser from navigating to the href location.  If Javascript is not running the browser will just navigate to the ‘/book/details’ page.

The next part is where most people might get lost.  But, if you are using a modern MVC framework (why wouldn’t you be?), then you should be fine.  Or, at the very least, you should be implementing the view decorator pattern in some form.

Basically, your controller (or page) should be able to detect whether or not the request was made via AJAX, the XMLHttpRequest object.  Most javascript libraries make this easy by adding a special request header, ‘X-Requested-With’.  If your library does not do this, you should be able to manually add the header.  By checking this header, you can easily determine whether it is AJAX you are dealing with.

In PHP:

     
     function isAjax() {
       return $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest';
     }
     
     $book = Book->find($id);
     
     if( !isAjax() ) {
       include('includes/header.inc');
     }
    
   echo "
   

${book[title]

${book[description]}

"; if( !isAjax() ) { include('includes/footer.inc'); }

That is pretty straightforward, but the great thing is that most MVC frameworks will do it automatically!  But, what if we want to automatically create our links.  This is easy with the jquery library.  We will create a method that will run when the page loads, and add automatically add the functionality to our links (designated with the ajaxme class).

   
   
   

Keep in mind there are many situations where it is not possible to gracefully degrade an application.  In these cases a <noscript> tag should be used to warn the user that they are missing out on additional functionality.

Tags: , , , ,

No Comments