Become A CoccyxJS MVC Ninja – Mini Tutorial #4: Collection

coccyxjs_ninjaWelcome to the 4th tutorial in a series of CoccyxJS mini tutorials. In the previous tutorial we learned how easy it is to use the CoccyxJS Model component in a Web application for storing data. In this tutorial we will expand on that and use a Collection to store multiple data that we will pass to the View’s render method. 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.

Collections

Collections are light weight components that encapsulate arrays of Models which are stored in their “coll” array properties. Like Models and Views, they are manipulated by Controllers and their route handlers.

tutorial04.js

In your project’s root folder, specifically its javascripts folder, create a file named tutrotial04.js. In tutorial04.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 04.
 * Expands on tutorial 03.
 * Using a Collection to pass data to a View.
 */

(function(v){

    'use strict';

    //Implement a route handler for 'get /'
    var showIndexPage = 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 Collection's data which is an array of
        //days of the week objects as a parameter and it will wrap each
        //day of the week object's day property in a header tag
        //and render it to the page.
        var daysOfTheWeekView = v.views.extend({
            render: function(data){
                var self = this;
                data.forEach(function(dayOfTheWeek){
                    self.$domTarget.append('<h2 style="color: #00f">' + dayOfTheWeek.day + '</h2>');
                });
                //Return 'this' allows for chained access to
                //View properties when rendering to the page.
                return this;
            }
        });
        //Render the data to the DOM. Notice how we are taking
        //advantage of chaining!
        v.$('#container').html(daysOfTheWeekView.render(this.collection.getData()).domTarget);
    };

    //A simple controller that declares one route
    //and an init method that will be called immediately
    //before its route handler is called.
    //The route it will handle is 'get /'.
    //The function it will call is showIndexPage.
    var controller = {
        init: function(){
            //The data for the Collection.
            var data = [
                {day: 'Monday'},
                {day: 'Tuesday'},
                {day: 'Wednesday'},
                {day: 'Thursday'},
                {day: 'Friday'},
                {day: 'Saturday'},
                {day: 'Sunday'}
            ];
            //Create a Collection and initialize it with some data.
            this.collection = v.collections.extend();
            this.collection.setModels(data);
        },
        name: '',
        routes: {
            'get /': showIndexPage
        }
    };

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

}(window.Coccyx));

Add tutorial04.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>
    <script src="javascripts/tutorial03.js"></script>
    -->
    <script src="javascripts/tutorial04.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:

minitutoutput4

What Just Happened?

Lets break this down:

  • We declared that our Controller has an init method. A Controller’s init method is a very handy way to do one-time initialization and it is called only once and only when a Controller receives its first routing request. Here we are using the init method to create and initialize a Collection and add it as a property of the Controller. When the route handler is called the Collection’s data will be passed to the View’s render method.
  • In the Controller init method we create a new Collection by calling v.collections.extend(), and then we call collection.setModels(data) to initialize the new Collection with data. Notice how we passed an array of hashes, where each hash has a day property whose value is the day of the week that will be rendered to the DOM.
  • Just like in tutorial03.js the route handler creates a View with a render method which takes a single parameter whose value will be rendered to the DOM. This route handler, however, differs from tutorial03.js in that it extracts multiple data that are to be rendered to the DOM from the Controller’s collection property by calling this.collection.getData(), which returns a copy of the data that is stored in the collection.

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

With the conclusion of this tutorial we have learned about Models, Collections, Views and Controllers, which are the basic components for every CoccyxJS MVC application. In our next mini tutorial we will learn how to declare and respond to DOM events. 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