Load External JavaScript Files in on{X}

The other day I talked about the things I was playing with in on{X}. I like to use other frameworks or JavaScript libraries when I write my codez. Of course I’m going to want to do the same when writing rules in on{X}. This example shows how to load underscore.js for use in your on{X} rules.

(function() {
    device.ajax(
    {
      url: 'http://underscorejs.org/underscore-min.js',
      type: 'GET',
      headers: {
        'Content-Type': 'text/javascript'
      }
    },
    function onSuccess(body, textStatus, response) {
      eval(body);  
      if (_) console.log('underscore.js loaded successfully');
      yourCode(_);
    },
    function onError(textStatus, response){
      console.error('error code: ', response.status);
    });
})();

function yourCode(_) {
    var stooges = [{name : 'moe', age : 40}, {name : 'larry', age : 50}, {name : 'curly', age : 60}];
    console.info(_.pluck(stooges, 'name'));
}

This should work with most libraries that you can access anonymously and via HTTP.

Disclaimer: Use at your own risk, I’m still just learning how this all works. :)

Related:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Chris Missal

Oh hey, I'm a Senior Consultant for Headspring in Austin, TX. I've been working in software professionally since 2006 and I really, really love it. I'm mostly in the Microsoft world, but enjoy building computer things of all sorts (to be vague). When I'm not slinging code, I'm probably out and about slinging discs, bowling balls, or good beer with great friends.
This entry was posted in Android, JavaScript, on{X} and tagged , , , , . Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • Alper

    I’ll bite.  Is this an exception to eval is evil rule?

    • http://chrismissal.lostechies.com Chris Missal

      To be completely honest, I don’t know. I’m guessing it’s still bad to use here, but I’m comfortable running this on my phone. I should add the “use at your own risk” disclaimer maybe. I didn’t want to use it, but my want to load underscore.js outweighed my hesitancy to use an eval() in there.

      • Marco Angelucci

        Well you can always embed a version of it directly in the script if you don’t want to pull it down from someone else servers.

        • http://chrismissal.lostechies.com Chris Missal

          Good call, probably the simplest approach too. :P