Sunday, February 10, 2013

RequireJS walkthrough

New technology names and acronyms I knew them...


...yet lacking real knowledge on them, I feel I'm a phony :(


I'm lucky I'm in an awesome company if not a perfect company, there are many engineers in the company who already have knowledge on new technologies which I don't know (yet) ツ And it's refreshing to know that we are not as homogenized when it comes to technology choices, some uses in-house ORMs, some of us uses NHibernate, some of us don't stop at ASP.NET MVC, some are seeking how to engineer things better, and are learning or already knew client-side MVC technology like AngularJS, KnockoutJS, Kendo MVVM(PSA: MVVM is a tweaked MVC), and other technologies like RequireJS, AMD, CORS


It's becoming a regular occurence when I'm having conversations with fellow engineers and they ask questions that are impressive, yet I don't know the answers for. Case in point, there's the questions about if RequireJS can be used with AngularJS, can AngularJS do CORS, what's the difference between AngularJS and KnockoutJS. And on CORS topic, I can only muster a JSONP answer(which I already tried and works on AngularJS), I'm exposed hahah! A quick trip to wikipedia while writing this post says that CORS is better than JSONP.


AngularJS supports CORS as far as the browser supported it too. Even the poster child javascript framework that abstracts away (read: jQuery) browser inconsistencies don't have CORS support for IE8 and IE9, as Microsoft didn't put CORS support on IE8 and IE9 and made a competing technology to CORS instead: http://bugs.jquery.com/ticket/8283


But alas! Microsoft can't be that stubborn for far too long, finally they embraced what everyone else are implementing, IE10 have CORS support


There's goes my Microsoft-rant-once-in-a-while fix for the month! :p


Back to regular programming.


Out these technologies, one thing that sticks out like a sore thumb to me is RequireJS. RequireJS facilitates dynamic loading of javascript files from client-side without using server-side technology(e.g. ASP.NET MVC, Java, PHP, etc). If we are embracing client-side MVC more and more and making server-side technologies a second fiddle to our application stack, this is where we need a technology like RequireJS.


It's time to rectify my lack of knowledge on that awesome Javascript technology, time to stop being a perpetual catch-up, in this article I'll show you how to use RequireJS.


To start with, we need to get RequireJS from NuGet.


Then try out the following sample code, remove Default.aspx and create Default.htm:

<!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>RequireJS sample</title>
    <script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    
    <script src="/Scripts/require.js"></script>
</head>
<body>

    Service: 
    
    <select id="ServiceType">
        <option value="/Services/FirstClass.js">First Class</option>
        <option value="/Services/SecondClass.js">Second Class</option>
    </select>    `
    
    <hr />
    <input type="button" id="Something" value="Test the Service"/>


    
    <script>



        $(function () {
            var service = null;

            $('#ServiceType').change(function () {
                var path = $(this).val();
                require([path], function (c) {
                    service = new c();                    
                });
            }).trigger('change');


            $('#Something').click(function () {
                if (service != null)
                    service.saySomething();
                else
                    alert('Service not yet loaded');
            });
        });
    </script>

        

</body>
</html>



To load your javascript files you'll use require function, the first parameter is an array of javascript files to load, the second parameter(can have third, fourth parameter and so on, if you need to load multiple javascript modules) is where your function/class definition goes to. In the above code, we are treating the passed function as a class, hence the new c()




Enclose your javascript files in define function.

/Services/FirstClass.js:
'use strict';

define([], function () {

    function FirstClass() {
        this.saySomething = function () {
            alert('Welcome aboard!');
        };
    }

    return FirstClass;

});


/Services/SecondClass.js:
'use strict';

define([], function () {

    function SecondClass() {
        this.saySomething = function () {
            alert('yo!');
        };  
    }

    return SecondClass;

});


That's it! It's easy to use RequireJS


On next post, I'll show you how RequireJS can be used for dynamically assigning controller to AngularJS routing


Happy Coding! ツ

1 comment:

  1. when ever we run the command which r.js on windows7 then getting an error which says which is not external or internal command.Web Development Nyc

    ReplyDelete