Become A CoccyxJS MVC Ninja – Mini Tutorial #3: Model

coccyxjs_ninjaWelcome to the 3rd tutorial in a series of CoccyxJS mini tutorials. In the previous tutorial we learned how easy it is to use a CoccyxJS View component in a Web application for rendering markup to the DOM. In this tutorial we will expand on that and use a Model to store the message 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.

Models

Models are light weight components that encapsulate data. Like Collections, which we will cover in a future tutorial, and Views, they are manipulated by Controllers and their route handlers. Models store their data in their “data” hash properties and Models provide a rich array-like API that includes methods for initializing , getting, setting and deleting data properties. Today we will focus on initializing a Model with data and getting the data back out of it.

tutorial03.js

In your project’s root folder, specifically its javascripts folder, create a file named tutrotial03.js. In tutorial03.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 03.
 * Expands on tutorial 02.
 * Using a Model 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 Model's data which is 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(data){
                this.$domTarget.html('<h2 style="color: #00f">' + data.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(this.model.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(){
            //Create a Model and initialize it with some data.
            this.model = v.models.extend();
            this.model.setData({message: 'Hello World!'});
        },
        name: '',
        routes: {
            'get /': showIndexPage
        }
    };

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

}(window.Coccyx));

Add tutorial03.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>
</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:

  • 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 Model and add it as a property of the Controller. When the route handler is called the Model’s data will be passed to the View’s render method.
  • In the Controller init method we first create a new Model by calling v.models.extend(), and then we call model.setData({message: ‘Hello World!’}) to initialize the new Model with data. Notice how we passed a hash with a message property whose value is the message that will be rendered to the DOM.
  • Just like in tutorial02.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 tutorial02.js in that it extracts the message that is to be rendered to the DOM from the Controller’s model property by calling this.model.getData(), which returns a copy of the data that is stored in the model.

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 Collections and we will expand upon tutorial03.js by passing a Collection 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