Wednesday, June 12, 2013

We have routers

I am now beginning work on the second major screen of the app which is the writingdesk. So the first thing to do was to get a router for our app.

Router in Backbone is the same thing as the router in Django or other frameworks. It's job is to load the right view depending on the URL being visited. The URLs can either look like 'http://example.com/#dashboard' or 'http://example.com/dashboard'. If you, like me, find the first ones ugly, it is easy to switch to second kind. Just pass pushState as true when instantiating the router.

The catch is however that since the user can now bookmark this url or hit refresh, your server will also need to be ready to serve this URL if asked for. That was easy to achieve with my limited number of views and screens.

Currently I am trying to be figure out a good way for 1) loading of CSS files 2) loading a large template for the second screen. I had hoped that requirejs would have a plugin for css files as well but turns out that detecting when a CSS file has loaded is not possible with much reliability. Hence there is no official css plugin for requirejs.

Tuesday, June 11, 2013

You cannot REST all the time

In any app of reasonable size, there are going to be API endpoints other than the REST API points corresponding to resources. For example, there may be a special endpoint for importing files which may lead to creation of one or more resources.

It is however a good idea to have these endpoints speak the same language of codes and return values as the REST endpoints thus making the whole thing more consistent. With some tweaks to the aging FileUploader, which included adding support for csrf token in AJAX request, treating 201 as a success code, I have my import endpoint pretty close to create endpoint.

I also gave up a little more of my fear and removed the second call to the server for fetching the models in case an event of imported:publicaiton is raised. Now we are living the JS dream where we speak as infrequently to server as possible and be very snappy.

Time has also come for our app to get some routes.

Monday, June 10, 2013

Regarding callbacks when saving a Backbone model

This one stumped me for a while. Backbone allows you to specify success and error callbacks when saving a model. But if you go by the documentation, this is how you create and save a new model:

submitForm: function(e){
 e.preventDefault();
 
 var pub = new Publication({
  'title': this.$('input[name="title"]').val()
 });
 pub.save({
  success: this.onSuccess
 }) 
},

onSuccess: function(model, response, options){
 Vent.trigger('imported:publication');
 this.$('form').trigger('reset');
},

But with the above, while the model will be correctly saved, the success callback will not be called. Reason being, the first argument to the save call is mandatory unlike what the documentation says. So something like the following will work:

 pub.save({}, {
  success: this.onSuccess
 }) 

Notice the empty object being passed as the first argument. You can also pass null if you like that but I still get nightmares of NullPointerException from my Java days. So I try and steer clear of it.

The next problem you may run into is that `this` does not seem to be set to correct value in the callback. In general, any callbacks being called from non-backbone or marionette code will suffer from this problem. This can be handled by a call to bindAll while initializing the view:

initialize: function(){
 _.bindAll(this);
},

Another thing you will sooner or later start missing here is the lack of a 'onComplete' callback that gets called irrespective of success and failure. This callback is useful for things like enabling the submit button that you may have disabled on submission or removing the waiting icon.

Fortunately, the save method returns a jQuery deferred object. So we are free to set our own onComplete callbacks on it:

formSubmit: function(e){
 e.preventDefault();
 
 this.$('button').hide();
 
 var pub = new Publication({
  'title': this.$('input[name="title"]').val()
 });
 pub.save({}, {
  success: this.onSuccess
 })
 .complete(this.onComplete);
 
},

onSuccess: function(model, response, options){
 Vent.trigger('imported:publication');
 this.$('form').trigger('reset');
},

onComplete: function(){
 // Display the submit button again
 this.$('button').show();
}

In fact we can do the same for the success and error callbacks as well.

pub.save().success(this.onSuccess).complete(this.onComplete);


While passing a success callback or using the deferred to setup a success callback are identical, in case of error callback, if you do not specify one in the arguments, an error event is triggered.

Sunday, June 9, 2013

Moving towards a fully working Marionette app

Starting from the ItemView, I have finally converted my application to use marionette application at the top. With this, the overall structure has started falling in place.

One benefit of committing to a framework is that it can force you to some good practices. While building my API using Django view, I was constantly using @csrf_exempt decorator so that I don't have to deal with passing the csrf token while making AJAX requests. I said I will come back to it but never did. However with Django Rest Framework, this was not a possibility and so I ended up handling the issue.

As it turns out, it is surprisingly simple. The CSRF token is included in a cookie by Django whenever csrf protection is on. You just need to extract that cookie and include the CSRF token as a header in request. All the code required to do this is provided in the Django official documentation.

So with CSRF hurdle crossed, I was able to create a new Publication via my Marionette app via the API.

Looks like it is time to go back to DRF and check out the Pages level API.

Central Message Bus

So armed with Marionette and Eclipse templates, I made some good progress on the dashboard. The additional pieces provided by Marionette are not only helping in reducing boilerplate code, they are also helping me think more clearly about my application.

The dashboard now comprises of several independent views that talk to each other via a message bus. A message bus or event aggregator is something on which any object in your app can trigger an event or listen for an event. So instead of directly subscribing for events on each other, they now only talk to the message bus. This decouples them and makes them reusable.

For example, the Publication Importer view I wrote is reusable in two ways. One is that it can be embedded anywhere in the app and it should work. It is also a blueprint for how to write import views for other resources. It looked like I can factor out a base class from the view that can be configured/overridden for building any number of import views.

I started with converting the basic views to Marionette and I am slowly building up to a Marionette application. Tomorrow I hope to get to the point where I can start working on the main character in this cast - the writing desk.

Eclipse Templates FTW

What do you do when you find yourself writing the same skeleton code in almost every file again and again? Since I switched over to AMD style modules for javascript, using requirejs, following is the common patterns in every file:


define([
        "jquery",
        "underscore",
        "marionette",
        ],
function($, _, Marionette){
 "use strict";
 
 var dashboard = Marionette.CompositeView.extend({
          ....

 });
 
 return dashboard;
 
});

Wouldn't it be great if this scaffolding could be generated with couple of key strokes? So I started digging into Eclipse and out came the templates. Not only most of the perspectives come with pre-built templates, you can define your own.

Defining a new template is simple. Go to Preferences and filter for templates in the left hand sidebar.



Click on New and create a new template:


Remember to give it a name you can easily remember. In order to use the template, you type the name and hit CTRL + Space and the name is replaced by the template. Best part is that when you change a $variable, all instance of it are updated. So in the above, when you replace object by the name of your JS Module, the return statement will also get updated automatically.

Marionette reduces the boilerplate code one has to write but some amount of it in inevitable. For those cases, there are templates. More than the time saving, it is the feeling of escaping the mundane that makes these very useful.

Saturday, June 8, 2013

Backbone is out, Marionette is in.

I know you are thinking that didn't take long. I agree that I am guilty of not making up my mind and then sticking with it. But not in this case.

As I said in my previous post, Backbone means a lot of decisions. Good thing is that it is already couple of years old and very successful. Which means it has drawn the attention of many very capable developers who not only saw the same issues but also decided to do something about them.

Now some of them went ahead and wrote their own libraries and frameworks like Spine.js, Angularjs and many many more. Each comes with their own pros and cons and many of them are more advanced. But there were others who decided to build on the foundation of Backbone itself. Marionette falls into that category.

The primary motivation behind Marionette, apart from improving the spelling skills of developer, is to reduce the boilerplate code in Backbone app. Though the name marionette seems to recover most of the reduced code.

But anyway, I have started to convert my 1 day old Backbone based dashboard to Marionette. So far so good. I will be back with more details tomorrow.