Home » JavaScript » Backbone.js » Why should we use server side in Backbone.js?

About Piyas De

Piyas De
Piyas is Sun Microsystems certified Enterprise Architect with 10+ years of professional IT experience in various areas such as Architecture Definition, Define Enterprise Application, Client-server/e-business solutions.Currently he is engaged in providing solutions for digital asset management in media companies.He is also founder and main author of "Technical Blogs (Blog about small technical Know hows)"

Why should we use server side in Backbone.js?

One of the challenges when building nontrivial Web applications is that JavaScript’s non-directive nature can initially lead to a lack of structure in your code. JavaScript is often written as a free-hanging and unrelated blocks of code, and it doesn’t take long before it becomes hard to make sense of the logic and organization of your own code. This becomes very much problematic when you are making a single page application(SPA). We can use server side scripting along with backbone.js to tackle this problem. Although this very approach creates problems of it’s own.

In this article we are going to discuss about applying server side scripting to the backbone.js and how to deal with the problems.

Backbone.js is a Java script framework known as MV* framework. This framework has the Backbone.sync function to perform CRUD (Create, Read, Update, Delete) operations. In order for a model object to perform these operations, it should have a property named ‘url’. The ‘sync’ function receives 3 arguments: method, model and options. Model objects also have functions that call the ‘sync’ functions, these functions are: ‘fetch’, ‘save’ and ‘destroy’. The function Save does both Create and Update operation: If the property id Attribute is defined, and the id Attribute is set, ‘save’ sends an update request, otherwise it sends a ‘create’ request. The content type of the request is ”application/json”.

WHY SHOULD WE USE SERVER SIDE IN BACKBONE.JS?

Backbone.js is a lightweight framework that addresses this issue by adding structure to JavaScript-heavy Web applications.

Self-contained building blocks

Backbone.js provides several classes (Model, Collection, View, Router) that you can extend to define the building blocks of your application. To build an app with Backbone.js, you first create the Models, Collections, and Views of your application. You then bring these components to life by defining a “Router” that provides the entry points of your application through a set of URLs.

Data Binding

With Backbone.js, you bind Views to Models so that when a Model’s data changes, all the Views bound to that Model automatically re-render. No more complex UI synchronization code.

Elegant REST Integration

Backbone.js also provides a natural / magical / elegant integration with RESTful services. If your back-end data is exposed through a pure RESTful API, retrieving (GET), creating (POST), updating (PUT), and deleting (DELETE) models is incredibly easy using the Backbone.js simple Model API.

DIFFERENCE BETWEEN CLIENT AND SERVER SIDE RNDERING:

Client-side rendered apps

If you’ve ever built a fully client-side rendered app, you are probably aware of its downfalls: slow loading/render times, and no useful search engine indexing of your pages.
Despite the downfalls, these apps are pretty straightforward to build:

The backend serves a super-lightweight html page: pretty much an empty ‘body’ tag with one or so ‘div’ elements that your JS app dynamically fills in. All of the data rendering happens via client-side templates that are attached as script tags to the html page.
This is great in that your app can get delivered to any JS-capable device and more or less run the same way. Of course, download times of JS bundles, mobile browser fetch order, and the speed of JS processing for your app will vary.

Server-side Rendered Apps

Here’s an overview of the necessary pieces for approaching a server-rendered app:
As expected, the server actually returns a heavier page to the client. It will consist of html representations of data that would have normally been rendered on the client-side via script-tag templates. Search engine crawlers will actually see the content when they arrive! Instant SEO boosts and a guaranteed increase in organic traffic to your pages. The client won’t have to download your entire JS app, parse and execute it, set up the router, instantiate the proper views and models, fetch the JSON data, and then finally render that data to see a piece of content. The content is all there when the client arrives – increasing the perceived speed of your page. The backend further utilizes the bootstrap able data that it has available to render more of the page.You now have more of a baseline guarantee as to when users will see your page’s content.

Although their are some downfalls to this technique also, as depending on how you distribute the responsibilities of your api and html rendering services, your backend has to think about both JSON and HTML-fragment caching. Along with fragment caching, you now have to apply the hard problem of cache invalidation to both your JSON and HTML at the cache. The server also can’t understand the Underscore templates.To recover from this problem we can use node.js.

Now we have understand a little bit of the upsides and downsides of client side and server side rendering. So, how do we figure out how are our requests will be handled by the server?
Let us look through it.

HOW DOES THE SERVER KNOW WHAT REQUEST TYPE IT RECEIVES?

The client-side developer specifies one ‘url’ only per model. The server-side program can determine the type by checking the value of $_SERVER[‘REQUEST_MOTHED’]:

  • ‘GET’ – a read (or fetch) request.
  • ‘POST’ – a create(save a new model) request.
  • ‘PUT’ – an update(save existing model’s detail) request.
  • ‘DELETE’ – a delete(destroy) request.

WHAT TO SEND AND HOW TO READ?

Backbone.sync uses AJAX to send requests to the server. What you have to pass is the method and model. You better not skip the 3rd arguments, options, which contains at least two member:

  • ‘success’ – a function called when the server processes the request successfully.
  • ‘error’ – a function called when the server fails to process the request.

READ REQUESTS:

If you send a ‘fetch’ request, specify ‘data’ in the ‘options’ argument, for example:

myModel.fetch({
data: {‘attr1′:’value1′, ‘attr2′:’value2′, … , ‘attrN’:”valueN’},
...

IN THE SERVER SIDE:

The request attributes are taken from $_GET or $_REQUEST, as usual.

SAVE REQUESTS:

Send the attributes and the options.
For example:

myModel.save(myModel.attributes, {...

IN THE SERVER SIDE:

The data should be read from the file “php://input”, a filename used for reading data from the request body. The content is a string, and should be parsed, but since the incoming request data is JSON encoded, you should use the PHP method “json_decode”.
For example:

$post_vars = json_decode(file_get_contents(‘php://input’), true);

DESTROY REQUESTS:

This time, set the ‘data’ member of the options argument to a JSON string. For example:

Backbone.sync(‘delete’, myModel,{
data: JSON.stringify(myModel), .... } );

IN THE SERVER SIDE:

This will delete the saved data that we have in server previously. For example:

$post_vars = json_decode(file_get_contents(‘php://input’), true);

SENDING A RESPONSE TO THE CLIENT:

The response is everything the server side application prints to the standard output. You should print your response data encoded into JSON, as follows:

echo json_encode(responsedata);

READING A RESPONSE:

The response returned from the server is the first argument passed to the ‘success’ callback function. It is not a model object, and you should get values from there using the method ‘get(attr-name’ or the member ‘attributes’.
For example:

{success: function(msg){
switch (msg.get(‘status’)){  ...

Although in the above we have discussed many pros and cons for using server side scripting and how to use them. There are many other ways to use it to tap in the maximum potential of using server side scripting.

Some related articles :

Reference: Why should we use server side in Backbone.js? from our WCG partner Piyas De at the Phlox Blog blog.

Do you want to know how to develop your skillset to become a Web Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. Building web apps with Node.js

2. HTML5 Programming Cookbook

3. CSS Programming Cookbook

4. AngularJS Programming Cookbook

5. jQuery Programming Cookbook

6. Bootstrap Programming Cookbook

 

and many more ....

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Want to take your WEB dev skills to the next level?

Grab our programming books for FREE!

Here are some of the eBooks you will get:

  • PHP Programming Cookbook
  • jQuery Programming Cookbook
  • Bootstrap Programming Cookbook
  • Building WEB Apps with Node.js
  • CSS Programming Cookbook
  • HTML5 Programming Cookbook
  • AngularJS Programming Cookbook