Tuesday, December 25, 2012

Backbone JS + Chrome App [manifest version 2]

Hello World!!, YAJSBP :)
QUOTE: Getting to know a library or a technology is pretty easy, but things get reversed when you want to apply the same which you felt you knew :)
In this blog post I'll take you through some integration challenges I faced while developing a chrome app along with backbonejs

So, I got to know about this guy Backbone.js an year before at jsFoo 2011.
The moment I noticed him, I visited his birthplace and got an overview of him.
Then I felt that I could claim I know backbone.js. Later realised it was too early to say that.
An year after I decided to try this guy and started developing a chrome app[Features Recorder].
Then I faced the following small challenges[on integerating backbone with chrome app] which I solved my own way :P

Problem: 1 Chrome App manifest version 2 doesn't allow eval or new Function
Error: Uncaught Error: Code generation from strings disallowed for this context
Take a look at Chrome app Content Security Policy

Why do we need this?
Underscore.js microtemplating uses new Function syntax for compiling the templates
Note: The problem might persist with other templating options too

1. As mentioned in the CSP page, relax the rule against eval and related functions
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
2. As I just used underscore.js microtemplates. I pre-compiled my templates offline [not in the app]
var source = _.template("My template code").source
//assigned the source to template property of the view
//This solved the problem
 initialize: function () {},
 template : function(obj){ //Precompiled template code
    var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};
    ((__t=( title ))==null?'':__t)+
    return __p;
3. Refer this blog

Problem: 2 window.localStorage for offline packaged is disabled
Problem: 3 chrome.storage is asynchronous [get & put are async as ajax]

Error: "window.localStorage is not available in packaged apps. Use chrome.storage.local instead."
I planned to build a offline packaged app.
But this error stunned me up as I can no more use local storage adapter for backbone

I built my own localstorage adapter for chrome.storage
As the storage works in async way, callbacks for functions like model.save and create remained a must
var options = {success: function () {  }};