Thursday, June 13, 2013

PushState, RequireCSS and RequestResponse

Today was the day of lots of new things. As I mentioned yesterday, I was in the market for something that will help me load my CSS.

While I agree that requirejs is a great tool to manage js dependencies, lately I am feeling that it leaves the job half done. A modular piece of JS, in many cases, will come with accompanying CSS and html templates. For example, almost every jquery plugin has a JS and a CSS file. Requirejs provides no API for declaring dependency on a whole module.

One way to achieve this with rjs is as following. First find a rjs plugin that loads html templates and css. Then write a wrapper module declaring dependency on both js and css. Now use this wrapper module wherever you needed the original. But this means writing a wrapper for every plugin or library you want to use. Given that rjs wants one module per file, this can mean a lot of files! One way of working around that is:

define('external', [], function() {
    var exports = {};
    exports.plugin1 = {
      ...
    };

    exports.plugin2 = {
      ...
    };

    return exports;
});
Then we can add a dependency on 'external' and use the required module. But now every external module will be loaded as a dependency for your module which is again not very palatable.

Loading CSS using RequireJS

For loading CSS, there are some plugins available. The primary issue is that a lot of modern browsers seem to be lacking a onload event on link elements. This means while it is easy to add a link element in the dom and thus load the CSS, there is no way to know when the sheet has loaded. One workaround is to keep polling the dom stylesheets to see if the new sheet has come in. The other approach is more clever. You create a script tag and use the css url as src. Browser loads the css and tries to interpret as a script and throws an error. So the onerror event on script tag can be treated as the onload for the css file.

There are bunch of drawbacks. One is that onerror gets called for 404 errors also. This means that the sheet was not found. This can be overcome with checking for the presence of stylesheet in the dom.

The other issue is that invalid script tag throws errors in the console. The workaround for that is to use img tag instead of script tag. With img tag, there is a non-threatening warning in the console and that's it.

There are couple of rjs plugins available that implement the above ideas: RequireCSS & CSSLoader. I am using a fork of RequireCSS that uses the img tag technique described above.

RequestResponse

RequestResponse is a simple object on which you can do two things:
  • set handlers for particular requests by name
  • make a particular request. The handler for the request will be executed and response returned.
Marionette applications come with a RequestResponse object on them. One use I am making of them is to make a central datastore for my models and collections. All other parts of application request the data from this central place. Updates are also done in the datastore. Other components use events to indicate what needs to be done.

This means any changes to a model or collection are immediately propagated to all the views. It also helps in supporting both the option of getting data: through a bootstrap variable dumped by the server in initial file or through a fetch from server.

// datastore module

var store = {};
// The library for the current user
function getLibrary(){
 if(!store.library){
  if(typeof pubs === 'undefined'){
   store.library = new Library();
   store.library.fetch();
  }
  else{
   store.library = new Library(pubs);
  }
 }
 return store.library;
}

var reqres = new Backbone.Wreqr.RequestResponse();
reqres.setHandlers({
 "collection:library": getLibrary,
 "model:publication": getPublication
});

return reqres;


// using the datastore in a view
// Request the library collection to be displayed
this.collection = DataStore.request("collection:library");

This pattern is useful when trying to build support for pushstate in your application. In case of pushstate, the view can either be rendered directly from the server or it might be reached through some interaction on the frontend. If the view is being rendered on the server side, it makes sense to provide the bootstrap data along with the template thus avoiding a extra call for data fetch. On the other hand, if we reach the view through some frontend interactions, we have to fetch the data from server through an AJAX call. A central datastore encapsulates the logic of doing the right thing in both the cases.

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.