Opinionated File Structures for Vanilla JS?

Well, I have to admit, it’s still a WIP and I’m still trying out different approaches to see what works and what doesn’t. Backbone itself isn’t strongly opinionated, but it does give you some components to help separate the different concerns of your application and so that’s really what I was imitating with my own code.

Basically, you have models and views (Backbone also has collections and routers, but I’ve not implemented those yet in my app). Models are responsible for containing your data, and saving/loading that data from the server. Views manage specific sections of your UI - they are where you attach your DOM event handlers and update the page. These components can also emit their own events which you can listen for.

An example of this from my app would be the ‘current project’ display. I have an area of the screen which displays the current project name and some other details. The view object that manages that part of the UI listens to the the current project model for changes and updates the display accordingly.

I find that structuring the app along these lines makes it easier to manage, as all the code that interacts with a certain part of the page is kept together within a view object. If something is not working correctly, you know where to look, rather than potentially having jQuery calls sprinkled throughout your code that may be touching the same part of the DOM.

As for the file structure, I keep my JS files organized into folders by type (e.g. View, Model etc.) For larger applications it seems to be more popular to group files according to the part of the application functionality they relate to (e.g. Users, Projects, Portfolio).

If you’re not come across it before, I’d recommend taking a look at the TodoMVC project. They take a basic to-do list app and provide versions created with different libraries/frameworks for comparison. There is a vanilla JS version, and a jQuery version that you might be interested in.

1 Like