Tweet about this on TwitterShare on FacebookShare on Google+Share on StumbleUponShare on TumblrShare on RedditPin on PinterestEmail this to someone

We have done some basic stuff by now, and in this part will try to show few UI elements on the page using Backbone.js. First I assume that you have gone through previous post because this is a continuation of that. As you’ve seen in sample UI so far, there are two sections (apart from header), that we’re not manipulating through Backbone yet.

Sections of the View

Sections of the View

For a moment forget about the labels given. Here we have two sections ‘Category Search panel’ where we place some input controls so that user can click on ‘search’ button to get categories from the server, and in later tutorial few working text boxes so that you can type code or name of the category(ies) he wishes to retrieve. ‘Category Search results’ area, will be used to display categories returned by server, and some buttons to let user to add/delete/update those categories, also we can assume both these sections together as our main view (ex: CategoriesView or CategoryMainView ).

Now we will write some code.

A sip of Coffee with Laravel and Backbone - Book

 

Step 1 – Implement Backbone.js Models

It’s better to have a model to store search criteria, we can also use this model to notify other parts of the main view for some actions to take place. We also need a model to represent single ‘category‘ which is UI representation of ‘Category‘ object that we receive from the server.

Open ‘public/coffee/category/models.coffee’ and add following code.

Note that all these models are inherited from our BaseModel. Also we use app.BaseModel since when it comes to this script we have it inside ‘window.app’ object. Finally as in previous post we add these two classes to the app object as well.

urlRoot: represents server url which needs to be accessed by this model to get/post/put/delete objects of type Category. Backbone is wise enough to append necessary parameters to this url to work it properly.

defaults: section initializes some default values for few properties that this Model going to contain. we need to keep ‘code‘ and ‘name‘ for the category and we initialize them with empty strings.

CategorySearchModel’  is to represent UI specific model to keep user inputs temporarily so that we can pass them to server in order to search categories if required. We can also use this model to notify events to other views. (since the View attached to search panel is not going to access other view’s DOM elements; we could but we should avoid it whenever possible)

Save this and issue coffee compile command. Open Browser and go to http://lbc.dev/category url. Open developer tools window and console. Type as below

 

Test Category Backbone Model

Test Category Backbone Model

 

set’ is Backbone.Model method where you can assign a value to a property. So we set ‘code’ and ‘name’. Then we call .save() – this is also a Backbone.Model method, what it does is it sends a HTTP POST message to the server, to make sure just switch to Network panel and check the request and response.

Watch HTTP Request and Response

Watch HTTP Request and Response

HTTP Response from Server

HTTP Response from Server

Notice that we have even got server side representation of Category object and automatically assigned it to ‘CategoryBackbone.Model, and you see new valid ‘id’ value. To make sure just call dump() method. and see what has changed in our model.

Populated Category Response

Populated Category Response

Now you see how easy to save using Backbone.Model.

Step 2 – Implement Backbone.js Collections

We will now define Backbone.Collection to keep category set. Open ‘collection.coffee’ file and add following code.

Now you should understand what this does. Two new things are

url: This is similar to urlRoot for Backbone.Model but in this case it is for the collection.
model: When we define a collection we need to specify which type of model that is stored in this collection. Since this collection to store instances of app.Category. we say  ‘model:app.Category

Save the file, compile and refresh browser, open developer tool console.

 

Test Category Collection

Test Category Collection

Note that we don’t have any objects inside the collection initially. ‘fetch()‘ is Backbone.Collection method to send HTTP GET request to the url we define in ‘url‘ property of the collection and populate itself. You can see network request above as well, also after the fetch() now you could see array of Category objects inside the collection. You can simply get one object by its ‘id‘ (which return app.Category type object in this case) and dump() it as well.

Step 3 – Implement Backbone.js Views

Finally for this post, will load some UI sections to the page. Even though we know how to save, retrieve data using models and collections will not plug that into Views during this part. But hopefully in next few posts of the series.

As we did with Blade templates we can define UI sections as templates. Then load and render them, insert them into main view using Backbone.Views, we can even reuse these templates. Let’s define two templates one to represent ‘Search panel’ and one for Result area’ and hook them with Backbone.Views. Finally will write a Backbone.Router to initialize these views and make them to render.

Open ‘application/views/category/index.blade.php‘ and modify the ‘content‘ section to include two new <script> sections.

 

This is how we define templates inside <script> tags with type=”text/template” so that these will not be rendered automatically by the browser, instead we could use them get loaded using javascript and insert into main DOM whenever required. Other than that there’s nothing new in these HTML (for now). As you can see ‘tpl-category-search‘ section is form element with two input boxes and two buttons. Please note that I’m using twitter bootstrap classes and elements. ‘tpl-category-results‘ template has a table to show our results and we have completed table header but not the table body, that is yet to be filled.

Then open ‘views.coffee‘ file, add this code but we will modify it as we move on.

I hope comments explain what each view responsible for. Now let’s add some more code to our views.

In CategorySearchView we have new property ‘el‘. This represents to which HTML element the view get attached or in other words area belongs to this view. As you have seen in ‘index.blade.php‘ file there is a <div> element with the id ‘search-area‘. So we need whatever renders by CategorySearchView to be placed inside this div tag. You can use normal CSS/jQuery selector format for ‘el‘. Every view has ‘initialize‘ method which is invoked when we create new instance of that View type, this is a good place to put some initialization code that we have related to the view; or best place to call render() method which is mainly responsible for rendering the view output and display it on the HTML page. Here I have done the rendering part inside initialize() instead of render(). Why? because this is one time rendering, I just need to load HTML section inside the template and place it into <div id=’search-area’> tag. I normally use render() method to render the UI when there is a change in its model or collection after we initially loaded the view. initialize() is called only once but render() can be invoked whenever we need, so I put logic to load the template and output inside initialize() method. in Line 7: I refer jQuery wrapper of el element and clear it’s inside content. in next Line I load search panel template using jQuery, gets it html content and insert it into el element. So now this should show what we had inside the template in HTML page. Finally I call render() method as well in case we add some model or collection to this view later and need to render those to the UI.

CategoryResultView also has the same logic except it uses <div id=’result-area’> as its UI element and template that it loads and insert is ‘tpl-category-results‘.
Finally our main view (CategoriesView) is responsible of creating two instances of above views in the initialize method.

Step 4 – Implement Backbone.js Router

We will now define the router. Router is the starting point of the execution flow. It’s like main() method in most programming languages. This is where user’s browser url selection events first come. (mostly as a url or url segment)
Open ‘public/coffee/category.coffee‘ file and include following code.

We define new router extended from app.BaseRouter and we give it a router table. We actually need only one entry in this example but in order to show you what it does I added two.

routes: indicates which method to invoke when user access a particular url (or segment). As you know url to our page is http://lbc.dev/category. So its default route segment is empty. We indicate it by creating a route entry with empty string (”). In order to explain other variations, I added another entry called ‘main’ which again executes same ‘showCategoryView‘ method, but this time you have to give the url as ‘http://lbc.dev/category#main‘.

Inside the showCategoryView method we just create new instance of CategoriesView.

Finally we have jQuery() section which automatically executed when the page is loaded. This is where execution first starts when HTML document is ready. Here we create new CategoryRouter instance and call Backbone.history.start() method so that Backbone knows when to dispatch routes.

That’s all. Just compile your coffeescripts and open http://lbc.dev/category url in your browser. You will see nice UI.

UI Rendered Using Backbone Views

UI Rendered Using Backbone Views

 

A sip of Coffee with Laravel and Backbone - Book

Posts of this series
Laravel, Backbone.js + Coffeescript Tutorial Part I – Introduction
Laravel, Backbone.js + Coffeescript Tutorial Part II – Setup
Laravel, Backbone.js + Coffeescript Tutorial Part III – Install Laravel
Laravel, Backbone.js + Coffeescript Tutorial Part IV – Database
Laravel, Backbone.js + Coffeescript Tutorial Part V – Data model
Laravel, Backbone.js + Coffeescript Tutorial Part VI – REST API
Laravel, Backbone.js + Coffeescript Tutorial Part VII – REST API
Laravel, Backbone.js + Coffeescript Tutorial Part VIII – Views
Laravel, Backbone.js + Coffeescript Tutorial Part IX – Coffeescript
Laravel, Backbone.js + Coffeescript Tutorial Part X – Backbone
Laravel, Backbone.js + Coffeescript Tutorial Part XI – Backbone
Laravel, Backbone.js + Coffeescript Tutorial Part XII – Backbone
Laravel, Backbone.js + Coffeescript Tutorial Part XIII – Backbone

Tweet about this on TwitterShare on FacebookShare on Google+Share on StumbleUponShare on TumblrShare on RedditPin on PinterestEmail this to someone