We all want to write better code. One that is easy to read, understand and extend. Finding the path to good code might not be trivial and is sometime achieved by searching out side of the box.
One of the best things about Backbone is how predictable its code is. Each Backbone.View has the same structure. This makes the code dead simple to understand, no matter which view you’re looking at.
UIViewControllers however, are a different story. UIViewControllers are unpredictable. Some will refresh the UI on viewWillAppear where others will do so on viewDidAppear. Some will only update the UI once on viewDidLoad. We must hunt down all of the viewDid/viewWill methods and figure out what’s going on.
Although Backbone is not a 100% MVC (Model-View-Controller) framework, it still makes handling data and UI easy. Backbone makes it easy to observe changes to a model (an object holding data) and act upon them. We use this feature to ensure the UI is always showing the most updated data.
Backbone.Views are predictable. Take a look at the following typical view:
It’s very short, but accomplishes a very common and important task in apps. The task of keeping the UI updated to reflect the changes in the model’s data.
The rules I follow with Backbone:
1. A view renders the UI when it loads.
2. A view observes changes to the model’s data and re-render the UI.
3. User actions change the model’s data and not the UI. The UI will be updated by observing the model’s changes.
With these rules in mind, let’s rewrite the code with Objective-C:
(This amazing library is used to simplify the model observation code)
Take a good look at this code. The view is always updated no matter what changed the model. The model could changed due to action taken by the user or by an async network request, but no matter what - the view will reflect the changes. The user will see the changes as they happen.
It just works.
The NSBackbone project on github shows this concept in action. You’ll love it.
Please share your ideas about bringing concepts from different programming languages to iOS development.