Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, August 28, 2017

Lodash Logic

If you're using Lodash, you have a handful of tools at your disposal for organizing logic into functions. This is a nice alternative to imperative if statements sprinkled throughout your code. For example, let's say that you only want to execute code if one of several choices is true. You could use the some() function as follows:

const choices = [
  { name: 'choice 1', value: true },
  { name: 'choice 2', value: true },
  { name: 'choice 3', value: false }
];

if (_(choices).map('value').some()) {
  console.log('true');
else {
  console.log('false');
}

The choices array represents the choices that we have available. The name property isn't actually used for anything in this code. The value property is what we're interested in here. We want to run some code if any value is true.

To do so, we're using an if statement. With the help of the map() and some() Lodash functions, we can easily check for this condition. In this case, the statement evaluates to true because there's two true values in the array. We can also check to make sure that every value is true before executing a piece of code:

if (_(choices).map('value').every()) {
  console.log('true');
else {
  console.log('false');
}

In this case, the else path is followed because not every value is true.

The _.some() and _.every() functions are helpful with simplifying the conditions evaluated by if statements. For example, _.some() provides the same result as chaining together a bunch of logical or (||) operators. Likewise, _.every() replaces logical and (&&) operators.

The result is that instead of having to maintain the condition that's evaluated in the if statement, we can simply add new values to the choices collection. Essentially, this is a step toward declarative programming, away from imperative programming.

Let's think about the if statement used above, and what it's actually doing. It's calling console.log() when some condition is true, and it's calling console.log() again when the condition is false. The problem with if statements like this is that they're not very portable. It'd be much easier to call a function with the possible choices as an argument, and the correct behavior is invoked.

Here's what this might look like:

const some = (yes, no) => (...values) =>
  new Map([
    [true, yes],
    [false, no]
  ]).get(_.some(values))();

Let's break this code down:
  • We've created a higher-order function called some() that returns a new function.
  • The returned function accepts an arbitrary number of values. These are tested with Lodash's _.some().
  • The some() function accepts yes() and no() functions to run based on the result of calling _.some(values)
  • A Map is used in place of an if statement to call the appropriate logging function.
With this utility, we can now compose our own functions that values as arguments, and based on those arguments, run the appropriate function. Let's compose a function using some():

const hasSome = some(
  () => console.log('has some'),
  () => console.log('nope')
);

Now we have a hasSome() function will log either "has some" or "nope", depending on what values are passed to it:

hasSome(0, 0, 0, 1, 0);
// -> has some
hasSome(0, 0, 0, 0);
// -> nope

Now any time that you want an if statement that evaluates simple boolean expressions and runs one piece of code or another, depending on the result, you can use some() to compose a new function. You then call this new function with the choices as the arguments.

Let's create an every() function now that works the same way as some() except that it tests that every value is true:

const every = (yes, no) => (...values) =>
  new Map([
    [true, yes],
    [false, no]
  ]).get(_.every(values))();

The only difference between every() and some() is that we're using _.every() instead of _.some(). The approach is identical: supply yes() and no() functions to call depending on result of _.every().

Now we can compose a hasEvery() function, just like we did with the hasSome() function:

const hasEvery = every(
  () => console.log('has every'),
  () => console.log('nope')
);

Once again, we've avoided imperative if statements in favor of functions. Now we can call hasEvery() from anywhere, and pass in some values to check:

hasEvery(1, 1, 1, 1, 1)
// -> has every
hasEvery(1, 1, 1, 1, 0)
// -> nope

Lodash has a _.cond() function that works similarly to our Map approach in some() and every(), only more powerful. Instead of mapping static values, such as true and false, to functions to run, it maps functions to functions. This allows you to compute values to test on-the-fly.

Before we get too fancy, let's rewrite our some() and every() functions using _.cond():

const some = (yes, no) => _.flow(
  _.rest(_.some, 0),
  _.cond([
    [_.partial(_.eq, true), yes],
    [_.stubTrue, no]
  ])
);

Let's break this down:
  • The _.flow() function creates a new function by calling the first function, then passing it's return value to the next function, and so on.
  • The _.rest() function creates a new function that passes argument values as an array to it's wrapped function. We're doing this with _.some() because it expects an array, but we just want to be able to pass it argument values instead.
  • The _.cond() function takes an array of pairs. A pair is a condition function, and a function to call if the condition function returns true. The first pair that evaluates to true is run, and no other pairs are evaluated.
  • The _.partial(_.eq, true) call makes a new function that tests the output of _.some().
  • The _.stubTrue() function will always evaluate to true, unless something above it evaluates to true first. Think of this as the else in an if statement.
We can use this new implementation of some() to compose the same hasSome() function that we created earlier and it will work the same way. Likewise, we can implement the every() function using the same approach.

For something as simple as the some() and every() functions, the _.cond() approach doesn't present any clear advantage over the Map approach. This is because there are exactly two paths. Either the condition evaluates to true, or it doesn't. Often, we're not working with simple yes/no logical conditions. Rather, there are a number of potential paths.

Think of this as a an if-else statement with lots of conditions. Suppose we had the following conditions:

const condition1 = false;
const condition2 = true;
const condition3 = false;

Instead of a simple yes/no question with two potential paths, now we have 3. Later on, we might have 4, and so on. This is how software grows to be complex. Here's how we would evaluate these conditions and execute corresponding code using _.cond():

const doStuff = _.cond([
  [_.constant(condition1), () => console.log('Condition 1')],
  [_.constant(condition2), () => console.log('Condition 2')], 
  [_.constant(condition3), () => console.log('Condition 3')]
]);

doStuff();
// -> Condition 2

For each of the condition constants that we defined above, we're using the _.constant() function in _.cond(). This creates a function that just returns the argument that is passed to it. As you can see, console.log('Condition 2') is called because the function returned by _.constant(condition2) returns true.

It's easy to add new pairs to _.cond() as the need arises. You can have 20 different execution paths, and it's just as easy to maintain as 2 paths.

In this example, we're using static values as our conditions. This means that doStuff() will always follow the same path, which kind of defeats the purpose of this type of code. Instead, we want the path chosen by _.cond() to reflect the current state of the app:

const app = {
  condition1: false,
  condition2: false,
  condition3: true
};

Instead of using _.const(), we'll have to somehow pass the app into each evaluator function in _.cond():

const doStuff = _.cond([
  [_.property('condition1'), () => console.log('Condition 1')], 
  [_.property('condition2'), () => console.log('Condition 2')], 
  [_.property('condition3'), () => console.log('Condition 3')]
]);

The _.property() function creates a new function that returns the given property value of an argument. This is where the _.cond() approach really shines: we can pass arguments to the function that it creates. Here, we want to pass it the app object so that we can process its state:

doStuff(app);
// -> Condition 3

app.condition1 = true;
app.condition3 = false;

doStuff(app);
// -> Condition 1

When doStuff() is called the first time, the console.log('Condition 3') path is executed. Then, we change the state of app so that condition1 is true and condition3 is false. When doStuff() is called again with app as the argument, the console.log('Condition 1') path is executed.

So far, we've been composing functions that use console.log() to print values. If you write smaller functions that return values instead of simply printing them, you can combine them to build more complex logic. Think of this as an alternative to implementing nested if statements.

As an example, suppose we have the following two functions:

const cond1 = _.cond([
  [_.partial(_.eq, 1), _.constant('got 1')],
  [_.partial(_.eq, 2), _.constant('got 2')]
]);

const cond2 = _.cond([
  [_.partial(_.eq, 'one'), _.constant('got one')], 
  [_.partial(_.eq, 'two'), _.constant('got two')]
]);

These functions themselves follow the same implementation approach, using _.cond(). For example, cond1() will return the string 'got 1' or 'got 2', depending on the number supplied as an argument. Likewise, cond2() will return 'got one' or 'got two', depending on the string argument value.

While we can use both of these functions on their own, we can also use them to compose another function. For example, we could write an if statement that would determine which one of these functions to call:

if (_.isFinite(val)) {
  cond1(val);
} else if (_.isString(val)) {
  cond2(val);
}

Remember, this approach isn't very portable. To make it portable, in the sense that we don't have to write the same if statement all over the place, we could wrap the whole thing in a function. Or, we could just use _.cond() to compose it:

const cond3 = _.cond([
  [_.isFinite, cond1],
  [_.isString, cond2]
]);

cond3(1);
// -> "got 1"
cond3(2);
// -> "got 2"
cond3('one');
// -> "got one"
cond3('two');
// -> "got two"

Using _.cond(), you can compose complex logic by reusing existing functions. This means that you can keep using these smaller functions where they're needed, and you can use them as pieces of larger functions.

Monday, December 14, 2015

JavaScript Concurrency

I'm pleased to announce my latest book — JavaScript Concurrency — from Packt Publishing and available on Amazon. This is unique book in that it's more than just a basic rundown of all the concurrency features available to our JavaScript code. Instead, the book uses features like promises, generators, and web workers, as teaching tools for thinking concurrently. There's no shortage of concurrency books out there that teach us how to think in terms of concurrency. This one is specific to JavaScript, and the theme aim is to show you how to write JavaScript code that's concurrent by default, instead of a bolt-on capability. Here's an overview of the chapters:

Friday, June 26, 2015

JavaScript at Scale

My latest book, JavaScript at Scale is available for pre-order now at Packt Publishing, and at Amazon. It'll be fully published in July 2015.

The JavaScript ecosystem is filled to the brim, to the point of overflowing actually, with libraries and frameworks. In this mix, there's some truly remarkable technology. In fact, it's hard to make decisions, given all the overlapping functionality and capabilities. What I've found over the past couple of years is that the architectural considerations get lost in all this choice. That is to say, that we may not be selecting the tool that's best for the front-end architecture we've set out to build. The choice of front-end technology is chosen more so on the generic capabilities of the framework. While TODO applications are a great springboard, to familiarize ourselves with the nature of the technology, that can only take us so far.

Monday, June 30, 2014

Repurposing Function Variables

Sometimes, I create too many local variables inside my functions. This can help with code-readability, especially if the function is involved. So what's the overhead in declaring these new variables that exist for a fraction of a second before they're garbage collected? Probably not too high — you're not going to see any perceivable performance improvements by declaring less variables.

Friday, April 25, 2014

Simplified Explanation of Generators in JavaScript

Generators, not yet available in all browsers nice ECMA 6 isn't final yet, are an interesting way to do iterative programming. That is, to generate data on an "as needed" basis. For example, let's say you have a large array to process, maybe reducing it to a smaller array. Before you start using that smaller array, you have to complete the loop that reduces it. With large arrays, you may want to start working with the reduced data as it becomes available, rather then waiting for the entire reduce process to finish.

Thursday, February 13, 2014

Working With JavaScript Object Defaults

The issue is a simple, yet annoying one. You want to access the property of an object, and work with that property value — perhaps calling a method on it, or accessing another property. The issue is that when an object property is undefined, errors happen. For example, if you're expecting a string or an array as a property value, the code would work fine if the property were initialized to an empty string, or an empty array respectively. The trick is, providing sane defaults on objects so that the clients using them don't blow up.

Tuesday, November 23, 2010

jQuery UI Overall Progress Bar

The jQuery UI Javascript user interface library has a progress bar widget used to indicate the progress of something.  That something can be anything, something happening locally in the browser or some server process.  Sometimes it is useful to show the overall progress of several smaller, but related tasks.  It would be nice if we could automate this with a specialized progress bar widget.

Thankfully, we can specialize the progress bar widget for this purpose.  We can create a progress bar that observes a set of other progress bars to measure and display the overall progress.  Here is an example of how we might go about doing this.

Here is the HTML markup:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>

        <title>Custom Progress Bar</title>

        <link href="jqueryui/css/redmond/jquery-ui-1.8.5.custom.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="jqueryui/js/jquery-1.4.2.min.js"></script>
        <script type="text/javascript" src="jqueryui/js/jquery-ui-1.8.5.custom.min.js"></script>
        <script type="text/javascript" src="js/overallprogress.js"></script>
        <script type="text/javascript" src="js/demo.js"></script>
        <script type="text/javascript">

            $(document).ready(function(){
            
                $("#sp1, #sp2, #sp3").progressbar();
                $("#ov").overallprogress( {subject: $("#sp1, #sp2, #sp3")} );
                               
                timer();
            
            });
        
        </script>
        <style type="text/css">
        
            .progress {
            
                width: 25%;
            
            }
            
            .container {
            
                padding: 10px;
            
            }
        
        </style>

    </head>
    
    <body>
        
        <h1 class="ui-widget ui-widget-header">Custom Progress Bar</h1>
        
        <div class="container ui-widget ui-widget-content">
            
            <p>Server Process 1</p>
            <div id="sp1" class="progress"></div>
            
            <p>Server Process 2</p>
            <div id="sp2" class="progress"></div>
            
            <p>Server Process 3</p>
            <div id="sp3" class="progress"></div>
            
            <p>Overall Progress</p>
            <div id="ov" class="progress"></div>
            
        </div>
        
    
    </body>
    
</html>

Here we create four progress bar widgets.  The first three are server processes that we want to show the progress of.  The fourth progress bar uses a custom progress bar widget that we'll show below.

Here is the demo Javascript, demo.js, that will simulate the server processes:


function timer(){

    var v1 = $("#sp1").progressbar("value");
    var v2 = $("#sp2").progressbar("value");
    var v3 = $("#sp3").progressbar("value");
    
    v1 += 5;
    v2 += 10;
    v3 += 5;
    
    if (v1 > 100) {
    
        v1 = 100;
    
    }
    
    if (v2 > 100) {
    
        v2 = 100;
        
    }
    
    if (v3 > 100) {
    
        v3 = 100;
        
    }    
    
    if ( (v1 + v2 + v3) < 300){
    
        setTimeout("timer()", 1000);
    
    }
    
    $("#sp1").progressbar("value", v1);
    $("#sp2").progressbar("value", v2);
    $("#sp3").progressbar("value", v3);
    
}

Here, we set a timer that will update the three server precesses.  The progress bar widgets are in turn updated.

Finally, we have overallprogress.js, our custom progress bar widget:

$.widget("ui.overallprogress", $.ui.progressbar, {

    options: {
        
        subject: false
    
    },
    
 _init: function () {
 
     $.ui.progressbar.prototype._init.call(this);

     var subject = this.options.subject;
     var overall = this;
        
  
  if (subject) {
  
      subject.bind("progressbarchange", function(event, ui) {
      
          var total = 0;
          
          $.each(subject, function(){
          
              total += $(this).progressbar("value");
          
          });
          
          overall.value(total/subject.size());
          
      });
  
  }

 },


});

The overallprogress widget takes a subject parameter when it is created.  The subject is observed by the overall progress widget.  In our example, it is passed a jQuery object containing the three regular progress bar widgets.  It then listens for progressbarchange events, on which, it updates the overall progress.

The reason we defined a new widget for this purpose is that it is generic enough to be useful in other contexts.  With custom widgets, we can encapsulate a lot of the common stuff that can be reused.  Here is what overallprogress looks like in action:

Monday, November 1, 2010

HTML Forms

Forms are useful tools for collecting information, whether they're physical, or or your computer screen. When we need specific bits of information, brevity is of virtue. Collecting these data fragments are why forms exist. A form value is as simple as a yes or no. They're as complex as a line or two of text. The web-equivalent of a paper form is the HTML form element. Given that a form is used to capture information, and, that is what it is good at, why aren't forms used more often in web pages? Not using a form element to gather user input is a classic example of reinventing the wheel. So why do we do it?

Maybe we don't like to use forms because we associate them with legacy-style HTML pages from the nineties. But forms aren't visual elements. Its the elements within the form that are displayed, the text inputs, the radio buttons, and selectors you can see. If a form is a non-visual element, that is, a structural element used to group others, why go out of our way to submit data by other means?

The ultimate purpose of a form element is pragmatic - it is functional, not presentational. There are two other data items forms store in addition to user input - the action and the method. The form action is a URI. A URI usually represents some data resource on the server. The form method corresponds to the HTTP method used to submit the form. When a form is submitted, the HTTP request is made with the stored action and method.

Another example of an element that stores an action and a method is an anchor tag. Links store the action in the href attribute. Just like forms, actions are URIs that represent resources on the server. So where exactly is the method stored? Links store the HTTP GET method implicitly. There is no way to click a link that sends a POST request without intervening with Javascript. Unlike forms, however, links take on the dual role of being both a functional and a presentational element - you can see links on the web page.

Since links can't send anything other than GET requests, we are more likely to use Javascript - assuming we want to make a POST request by clicking a link. This gives us full control over the HTTP request. When a user clicks a link, or any other element listening for click events, some Javascript function is triggered that will assemble the HTTP request. The request is then sent asynchronously behind the scenes. This work flow is especially easy with libraries such as jQuery. All it takes is a few lines of code to build the request and send it.

There is nothing inherently wrong with this approach - only writing code to do exactly what a form does is discouraged. This is especially true with GET requests that are sent as a result of user input. For example, we have a page that lists objects in a table. We also have a select element that filters the list by some field. When that selector changes, the page is refreshed with the new GET parameters. The request is triggered by binding the selector change event to a Javascript function. The function then builds the URI and sends the request. Alternatively, the select element is part of a form that stores the URI, and the method. Our function would simply submit the form.

Using forms as they were intended is good web-programming practice. They are perfect for collecting small pieces of information and map well to abstractions that exist on a server. Forms store HTTP methods, action URIs, group input elements, and assemble HTTP requests so that you don't have to. They exist for a practical purpose. Use them to your advantage and you'll be surprised at how much code you don't have to write.

Friday, September 24, 2010

Stateless User Interfaces

Is there such a thing as a user interface with no states? Normally, they have dozens of states, several of which may be active at any given moment. Envisage launching a program. You, the user, are given a starting point. This is the initial state of the user interface. From here onward, the changes in state are triggered by user input. Large programs, with many user interface elements, have numerous potential states while smaller programs might only have a handful. Desktop GUI applications are fundamentally different from web applications, including how different states are maintained. Is one ideal more complex than the other?

The visual elements of a user interface are called widgets. Widgets are the basic building blocks - larger widgets are composed of smaller ones. For example, a button is a widget. So is an input field. Both can be in one state or another. A text input widget can be in a focused state. This is what happens when the user clicks inside the widget. It changes state. Prior to being in a focused state, the text input must have been in another state. Probably a normal state. Another distinctive state found in the text input is when the user is actively typing. This puts the widget into a composite state since it must also be focused in order to type in it. The state of any user interface is the sum of all the widget states. This is a complex configuration.

Can a user interface exist without being in one state or another? An HTML page is an example of a stateless user interface. This is counterintuitive given that they contain widgets. Consider an input field. Does this widget have have any states in an HTML page? HTML widgets do have states but they are of no concern to the application. Only the browser. In a desktop application, widgets are created with a programming language. HTML is a markup language. Widgets created using a programming language have much greater control over the potential states of a widget.

For example, a desktop application might create an input widget. In addition to the basic construction parameters, id, default value, and so forth, an event handler might be set. The event handler is executed when the widget enters some state, like a hover state. Events are often triggered by changes in state. The event handler can do whatever the programmer deems appropriate. This flexibility exists in programming languages, not in markup languages.

If Javascript is considered a programming language, can widgets in an HTML page have states? Indeed, this is the intent of Javascript - when a widget changes state, a function can execute. Javascript libraries provide their own widgets that build on those found in HTML. These abstract widgets also have states. The goal of these custom widgets, and Javascript in general, is to make web pages look and feel more like desktop applications. So why is it that desktop applications feel better in comparison to HTML pages? CSS can add styles to a page that captivate the user. They can also destroy the whole user experience. Web pages with HTML and CSS that are done right can surpass the feel of some desktop applications.

A desktop application uses a single programming language and widget library. The developer has to consciously separate the logic from the presentation. A web application also uses a single programming language but places the presentation in a markup language. Here, the developer also needs to consciously separate the presentation from logic. But HTML is naturally separated from the application logic because it is a presentation language. A web application that uses a programming language for logic and a markup language for presentation is easy to understand because of this. Adding Javascript on top of the presentation means adding state to the page and isn't so easy to understand.

Stateless user interfaces aren't necessarily better than user interfaces with states. They have less complexity. The challenge, is to create something that looks good and is maintainable. Javascript, especially asynchronous HTTP stuff, lowers maintainability. Desktop applications are meant to have different user interface states that the programmer can use and react to. Javascript adds state to something that is supposed to be static. If the level of user interactivity is important, if you need to handle complex user interface state configurations, consider building a desktop application instead.

Thursday, June 3, 2010

jQueryUI Tab By ID

The jQueryUI tabs widget allows you to select a tab programmaticaly by using a 0-based index. This is handy because sometimes you want to direct a user to a tab without them having to click it. The select() method of the tabs widget allows us to do just that. However, having to keep track of the indexes for each tab doesn't really make sense and hard-coding the index value for a specific tab makes even less sense.

It would be nice if we could select a specific tab by ID. The following function does just that.
function select_tab_by_id(widget_id, tab_id){
jQuery(widget_id)
.tabs("select", jQuery(widget_id+" ul a")
.index(jQuery("[href="+tab_id+"]")));
}

select_tab_by_id("#my_tabs", "#tools");

Monday, May 31, 2010

jQuery String Contexts

The jQuery.each() iteration function is a powerful Javascript iteration utility. You supply a callback function that is executed for each element in the provided set. Additionally, the this object in the callback function is the current element. This can cause some subtle bugs in your code if your doing string comparisons.

Since this is an object and your callback wants to do a comparison as though this were a string, it will not always evaluate to true. Even when it should be. I found this rather annoying so I tried to make sure I was in fact comparing two strings. Sure enough, this.toString() fixed my problem. So, try using this if your strings aren't evaluating as expected inside jQuery.each() callbacks.

Wednesday, May 5, 2010

Themes Have Changed

Themes offer a look and feel that can enhance the appearance of a web application. Web application frameworks usually provide a framework for building themes along with a few pre-built themes. Themes in web applications have two components to them; the HTML markup for the structure of the page and CSS styles that actually change the look and feel. Wait a second, if the CSS styles are responsible for changing the look and feel, what does the HTML markup have to do with the theme? Conceptually, it has nothing to do with the theme if it is strictly defined as the look and feel. This isn't the case with traditional themes most of the time. With some themes, not only are the look and feel different, but the entire layout is vastly different.

Lets assume that a theme is strictly look and feel. That is, we can change the look and feel of the entire application simply by changing the CSS stylesheet. These stylesheets don't typically contain layout definitions, just colors, fonts, etc. So has this idea been adopted by many frameworks if any?

jQueryUI is a really good example of themes in practice. The CSS framework offered by jQueryUI is strictly a look and feel framework. There aren't any layout restrictions imposed by the CSS definitions. The jQueryUI CSS framework exists for the purpose of adding theme capabilities to the widgets in the jQueryUI library. The framework is flexible enough to be useful with HTML elements that fall outside of the widget set.

CSS classes inside the jQueryUI famework dictate the look and feel of the user interface. There really aren't any restrictions on what elements these classes can be applied to. If you have a container HTML element with several jQueryUI widget descendants, the widgets will have a distinct look and feel while the container element does not. It turns out that the container element can in fact share the same theme as the widgets by giving it an appropriate class from the CSS framework.

By eliminating structural layout requirements from the theme, you add a new level of flexibility. Javascript widgets actually look like they belong in the application. Also, by basing themes entirely on CSS styles, we make creating new themes much easier as well because the classes are standardized and there are no layout surprises. jQueryUI has proven to be very powerful theme-driven user interface framework and it looks as though it will continue to improve into the future as the widget set is expanded.

Wednesday, April 7, 2010

Language Popularity

According to the TIOBE index, the C programming language is back at number one for popularity. This comes as no big surprise as the language has thrived for decades due to it's simplicity. Also, according to the index, Python and Javascript are down. This seems strange since these two languages are huge in the web application space.

Monday, April 5, 2010

Hashing URIs

Clients of URIs often need to specify some sort of client parameter that is returned as part of the HTTP response. This parameter is intended to preserve the application state by encoding it into the URI.

A common practice is instead of passing the client state as a GET HTTP parameter, to provide the client state as a hashed URI segment. This segment would represent the client state. It is a preferable URI practice because the application state is still encoded as part of the resource URI but doesn't need to be sent to the server.

One aspect of this practice to be weary of is mistaking application state for resources. If the intent is to use the application state as the hashed URI segment, only use it for application states and not data resources.

Wednesday, March 31, 2010

jQuery Proxy

The jQuery.proxy() method allows event handlers to use the this object as something other than the event object itself. That is, you can change the context of a specified function. Some view this technique as somewhat dangerous. This is probably true if not treated with care.

If you're a developer coming from another object-oriented programming language, you're probably used to the this object referring to the current object or self. The whole purpose of the jQuery.proxy() method is to change that meaning.

It can be quite powerful in certain situations where the event doesn't provide all the data required by the event handler. Or maybe the original event object provides nothing of value at all and it is beneficial to use jQuery.proxy() everywhere. In this case you would only be updating some application model instead of reading the event properties. All you would care about is that the event occurred. Either way, useful feature to have available.

Thursday, March 25, 2010

HTML Reuse

One of the great features of any web application framework is the HTML template. These templates allow developers to inject variables into the page. In fact, most templates allow logic to be placed directly into the HTML page (which isn't a good idea, but not really the point here).

The server, by using HTML templates, can iterate over data sets and churn out HTML that is sent to the browser. This, in effect, saves us from storing the static page structure that is then sent to the client.

This is all well and good on the server side, but what about the client? It is given a static structure to display. The browser, behind the scenes is rendering the HTML into pixel values but the HTML itself is static.

This means that HTML that can often be computed is in a static form instead. Would it not make more sense to have the Javascript of a web application build these display elements based on application data returned from the server? Maybe not the entire display but I'm sure there are many repetitive elements that can be computed rather than delivered statically.

Thursday, March 18, 2010

jQuery API Attributes

jQuery is an excellent Javascript toolkit for interacting with server APIs. Especially for RESTful, resource-oriented APIs. Each resource returned from such an API generally has a unique ID associated with it. This could be a database primary key or a UUID. Regardless, it is used to uniquely identify the resource so it may be referred to as a URI such as /resource/3495/.

jQuery web applications often build lists of user interface elements from resource lists. For example, /resource/list/ might return a list of resources in the for of (id, name). Once the jQuery callback has this list of id-name pairs, it can build an HTML list. The question is, how should the resource ID be stored in the user interface so that it can be used again as part of a resource URI if the user clicks a list element?

One solution is to store the ID directly in the DOM element when it is created. The benefit here is that the URI can be constructed from the click event. The event object itself has a currentTarget attribute which is our list element. Lets say we stored a uuid attribute as part of the list element. Inside the click event handler, we could do something like jQuery(event.currentTarget).attr("uuid"). This is all we need to build a URI for this specific resource.

Thursday, March 11, 2010

Handling Callback Variables

With Javascript applications that make asynchronous Ajax requests, does it make sense to store a global variable that indicates the callback that should be executed? That is, depending on the current state of the application, a different callback function may need to execute for the same API call. Should a global variable be set before the request is made and checked each time by the response?

That doesn't feel right to me. Neither does sending application data along with the API request just to be used by the callback. That would mean sending application state to the server which isn't a good thing as far as I'm concerned.

I like the idea of listening for certain events that the callback might emit during execution. The callback might emit a certain type of event each time it is run. The events are always emitted but the application may not always be listening. When the application is in a certain state, it will be listening. The handlers of these events could be considered secondary callbacks.

Wednesday, March 10, 2010

Javascript Limits

Is there a fundamental limit to the size and complexity of Javascript applications? Or are these rich, web applications just like any other program? If they work, they just work.

Javascript applications have an added problem in comparison to desktop applications. They aren't installed on a users hard drive. They need to be delivered through the we browser. They applications, the Javascript source files may be cached, but this only periodically saves in page load time.

Javascript functionality seems to be growing ever more complex. So where does it end? Will users just need to wait for the modules to download once the source size gets to be huge? Or is there another solution in sight?

Tuesday, March 9, 2010

Javascript Object Attributes

I find the initialization of Javascript objects to be awkward when an attribute name is a Javascript keyword. It is bad practice to require attribute names with a keyword as an attribute name but sometimes it is unavoidable. For instance, when constructing an object to send along as parameters in an HTTP request.

For instance, here is a Javascript object using a keyword as an attribute name:
var my_obj = {id: 5, interface: "nic1"};
The code will run fine but it feels as though it shouldn't. The alternative notation is
var my_obj = {"id": 5, "interface": "nic1"};
This doesn't feel right either. I find its always better to be consistent, whatever notation is used.