Skip to content Skip to sidebar Skip to footer

Checking For Undefined Variable With Underscore.js

I'm having a problem with Underscore.js templates and Internet Explorer. Here's part of the template which is causing trouble:

<% if ( typeof description !== 'undefi

Solution 1:

From the fine manual:

By default, template places the values from your data in the local scope via the with statement.

You can see what's going on using the compiled template's source property:

var t = _.template('<%= v %>');
console.log(t.source);​​​​​​​​​​​​​​​​​​​

gives you (tweaked for clarity):

function(obj) {
    var __t, __p = '';
    with(obj || {}) {
      __p += '' + ((__t = ( v )) == null ? '' : __t) + '';
    }
    return __p;
}

The with is the source of your problem:

JavaScript looks up an unqualified name by searching a scope chain associated with the execution context of the script or function containing that unqualified name. The 'with' statement adds the given object to the head of this scope chain during the evaluation of its statement body. If an unqualified name used in the body matches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a 'ReferenceError' is thrown.

So given this:

with(obj) {
    console.log(pancakes)
}

JavaScript will first look for obj.pancakes and if there is no pancakes property in obj, it will look for pancakes in the global scope. Apparently IE has a window.description value which represents one of the page's <meta> tags. Using your own namespace inside the template (as in the work-around) sort of negates what with does and keeps you from getting to the global window properties.

Solution 2:

If you typeof something and the something is null, object is returned. Try checking for null after checking for 'undefined'.

Post a Comment for "Checking For Undefined Variable With Underscore.js"