I'm building an extremely JS-heavy web application. I say it's JS-heavy, because the vast majority of the work going on is done on the client (although there is some syncing back and forth to the server using AJAX and XMPP).
This is my first time building something of this scale in pure JS (using jQuery), so I began by organizing my code using MVC in a manner modeled after Rails. For example, if the user clicks a button, a method is called in the Controller object, which pulls some data from the models, and which then passed the data a view function. I do this for pretty much everything, even trivial actions like showing a small popup.
After a few months of this, I feel like I'm not taking full advantage of the language. Should I really be rendering my views as if they are webpages?
It seems like it'd make more sense to break down the views into components, which would be instances of Javascript objects/functions. For example, instead of...
var itemListHTML = '<ul id="item-list"><li>item1</li><li>item2</li></ul>';
jQuery('#container').html(itemListHTML);
...I could instead have...
components.itemList.render();
So here, there's just a component called itemList
. Since all the data is stored on the client, these components could instantly access all of the data necessary to create and manage themselves. I imagine I would still use MVC, but there'd be no need for controller actions that are responsible for the entire view. If I want to refresh one part of the UI, I just call whateverComponentControlsThatArea.redraw()
and it re-renders itself.
I'm sure someone had done this before. Is there a name for this style of code organization? Any guides or best-practices for how to implement it?
There are a number of javascript MVC frameworks available now
JavaScriptMVC, PureMVC, Sammy.js for example.
Rendering of views or sub-views in normally handled through some kind of templating engine.
JavaScriptMVC has a module EJS, which is modelled on ERB, which I have found quite useful. Templates can be compiled into functions to speed things up for production.
There are other templating solutions too for example John Resig's Micro-Templating and many more
I recommend you use one of these frameworks if it's not too late. I've used JavaScriptMVC for a few projects now and can recommend it (The docs take some getting used to though)