Become A CoccyxJS MVC Ninja – Mini Tutorial #2: View

coccyxjs_ninjaWelcome to the second tutorial in a series of CoccyxJS mini tutorials. In the previous tutorial we learned how easy it is to use a CoccyxJS Controller component in a Web application for declaring and handling routing requests. In this tutorial we will expand on that and add a View to our application which will render markup to the DOM. But before we get on with today’s mini tutorial please follow the instructions at “A Series jOf CoccyxJS Mini Tutorials”, if you haven’t already, for setting up a project directory structure and installing http-server which we will use throughout this series.

Views

Views are generic components which applications use to render and remove markup to and from the DOM, respectively. Applications can also use Views to declare the DOM events that Controllers respond to. In todays mini tutorial we will focus only on rendering markup, leaving DOM event handling for a future tutorial. Views, like Models and Collections, which we will also learn about in future tutorials, are manipulated by Controllers and their route handlers.

Two common use patterns exist when working with Views:

  1. passing data that is to be rendered, whole or in part, to a View’s method which, by convention, is often named “render”, and
  2. returning “this” from the rendering method, allowing for “chained” access to View properties.

tutorial02.js

In your project’s root folder, specifically its javascripts folder, create a file named tutrotial02.js. In tutorial02.js paste the following code and save the file. We’ll discuss the code in a moment but it is so much better to see it played out first:

/**
 * CoccyxJS mini tutorial 02.
 * Expands on tutorial 01.
 * Creating a View that renders makrup to the DOM.
 */

(function(v){

    'use strict';

    //Implement a route handler for 'get /'
    function showIndexPage(){
        //We'll create a View that renders markup to the page.
        //We define a method for the View named render. We
        //will pass it a message as a parameter and it will
        //wrap the message in a header tag and render it to
        //the page.
        var helloWorldView = v.views.extend({
            render: function(message){
                this.$domTarget.html('
<h2 style="color: #00f">' + message + '</h2>
');
                //Return 'this' allows for chained access to
                //View properties when rendering to the page.
                return this;
            }
        });
        //Show the message. Notice how we are taking
        //advantage of chaining!
        v.$('#container').html(helloWorldView.render('Hello World!').domTarget);
    }

    //A simple controller that declares one route.
    //The route it will handle is 'get /'.
    //The function it will call is showIndexPage.
    var controller = {
        name: '',
        routes: {
            'get /': showIndexPage
        }
    };

    //Register the controller &
    //begin handling routing requests.
    v.history.start(true, [controller]);

}(window.Coccyx));

Add tutorial02.js to index.html

Open the index.html file, which is located in the project’s root directory, and then copy and paste the following markup into the file and save the file.

<!DOCTYPE html>
<html>
<head>
    <title>CoccyxJS Mini Tutorial Series</title>
</head>
<body>
<h1>CoccyxJS Mini Tutorial Series</h1>
<d id="container"></d>
    <!-- JavaScripts -->
    <script src="javascripts/libs/jquery.js"></script>
    <!-- Shim file has to be loaded before coccyx.js is loaded!!! -->
    <script src="javascripts/libs/shim.js"></script>
    <script src="javascripts/libs/coccyx.js"></script>
    <!--  Previous mini tutorials
    <script src="javascripts/tutorial01.js"></script>
    -->
    <script src="javascripts/tutorial02.js"></script>
</body>
</html>

Start http-server

Now open your terminal and make the project folder the current directory. Once you’ve done that start the server by typing http-server at the command line and hit enter. Depending on your operating system (I am running on a Mac) you should see something similar to the following:

Terminal

Run The Application In The Browser

Now open your browser and navigate to http://localhost:8080 and you should see the following in response:

minitutorialoutput02

What Just Happened?

Lets break this down:

  • First we created a View by extending the CoccyxJS View component, passing it an object “template” that defines the View we want it to create for us. We then assigned the returned View object to the variable helloWorldView.
  • In the View template that we passed to extend we created a method called render which takes a single parameter named message. In the body of the render method we wrapped message inside an h1 tag and called this.$domTarget.html, passing it the wrapped message and returned this to allow for easy chaining. Since we didn’t “tell” the View what it should use for the domTarget the View defaulted to using a plain div element and rendered our wrapped message to that div element while it was still detached from the DOM (see the Guide for a detailed explanation of detached and attached rendering and for how the View component creates its $domTarget property from its domTarget property).
  • Next, in our route handler we actually rendered the content of $domTarget to the DOM by calling v.$(‘#container’).html(helloWorldView.render(‘Hello World!’).domTarget). Notice how we are passing the value of message to the View’s render method as well as how we are making use of chaining.

(Note: In a real application it isn’t advisable to dynamically build markup using strings like we did here and instead we would probably chose to use one of the many templating libraries that are available.)

Now wasn’t that ezpz? Give yourself another pat on the back because you are one step closer to becoming a CoccyxJS Ninja.

What’s Next

In our next mini tutorial we will learn about Models and we will expand upon tutorial02.js by passing a Model to the View’s render method. See you soon.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s