Learning the anatomy of Backbone.js
I have been playing around with Angular.js last year and spent late nights making a website that can generate unlimited math questions. I slowly moved onto Backbone.js.
Backbone js is described as a library that provide structure to javascript heavy web applications.
After experimenting with Backbone js for the past 1+ week, to some extent I miss the ease of doing bespoke structure with just plain vanilla js. Simply start and built upon on whatever structure that you can think of. Of course you will have to deal with all the spaghetti code later on. But for simple websites I think any mid level javascript/jquery programmer will have no issue handling the codes.
But then.. I miss the structure, immediate binding that the Backbone MV* framework provides.
- Declare a new model with different params
- Declare a collection to store multiple instance of models. Instantiate the collection. By default the collection is gona be empty since no models are instantiated.
- Declare a view and give it a "tagName" with a "className" of your choice, and start to listen to the initialise and render events. Link the view to a model, in this case we are using a collection declared in (2) instead.
- Declare an app view. For the ease of implementation I will usually use #appview ID added to my body> tag and target the whole body. Not too sure if this is the best way to do it.
At this point, nothing is happening in the HTML yet. But alot of structure is added into place.
The view will run a render function when anything happens to the model. Any model that is added, edited, removed will cause the view to fire render again. And any logic that happens will get processed in the view.
It is only when you instantiate the model that was declared in (1) and add it into the collection that was instantiated in (2), then the view will show you something.
But I have afew questions:
- What if you have a multiple views pointing to multiple models. Will the file codes get very complicated? Or can it (somehow) still be handled by the same view? But then your views will get very huge and will try to do everything. Which is also another problem.
- The render event in the views, is really nifty. But if render happens so many times, won't it be a rather expensive (resource, memory intensive) function to run?
- What happen if I have a very complicated view? Or even a nested view? A view-in-a-view?
I guess this is something that I need to continue experiment on. But thus far its been a very humbling experience! :D
I am also very curious to hear what others think about MV*/MVC/MVVM into Javascript development and the most effective library you have used for logically organising your Javascript. Would be great to get a discussion on this, just leave comments at the bottom!