A Javascript Storage Pattern in Rails with Javascript Auto Include

Posted on April 22, 2009. Filed under: development | Tags: , |

One of the things I’ve often struggled with in web app development is the temporary storage of information.  I recently started using the Javscript Auto Include plugin, and I love this plugin, not only because it allows me to encapsulate my js logic, but also because it lets me have a temporary storage vehicle for each view.  If you haven’t checked out this plugin, what it does is allow you to create a structure for js that mirrors your view structure.  By using a strong namespacing structure and this concept, I essentially have a view that is a javascript file.  Combining this with jrails, allows for a very compact and efficient js file size (I’ll work on minifying my views later, which is one of the downsides of this approach).

Now, what makes this really cool is that I can namespace my views.  So I have

com.mysite.views = { }; // in javascripts/views.js

com.mysite.views.users = { }; // in javascripts/views/users.js

com.mysite.views.users.add_user = { }; // in javascripts/views/users/add_user.js

And in my add_user view, I can store values in the js object or have methods that I know will be defined.  In other words, I get the same scoping that I would if I were calling views in namespaces in RoR, allowing for very straightforward refactoring of my javascript.

Each js file only contains what is needed for that view or for views in the same package; common functionality is in the overall views.js file, which is always included (from the app layout).

So, temporary storage, smaller js files, unpolluted global namespace, better organized js files.  That’s a lot to get out of a rather simple plugin.

(Before anyone posts that this won’t work if the user has JS disabled, no it won’t, but in the site I am working on, having JS enabled is a requirement to even logging in.)

Make a Comment

Make a Comment: ( None so far )

blockquote and a tags work here.

    About

    Thoughts on technology, entrepreneurism, small business, finance, and global competition

    RSS

    Subscribe Via RSS

    • Subscribe with Bloglines
    • Add your feed to Newsburst from CNET News.com
    • Subscribe in Google Reader
    • Add to My Yahoo!
    • Subscribe in NewsGator Online
    • The latest comments to all posts in RSS
    • Subscribe in Rojo

    Meta

Liked it here?
Why not try sites on the blogroll...