Asked By: Anonymous
I am looking for pattern in Backbone js to switch between readonly and edit view. If the trigger for the view is external to the view then no problem I can create the appropriate view ( readonly or edit ) and render it, but in my case the trigger for the edit view will be inside the readonly view.
For example lets say I am displaying a Prescription and by default it is in readonly mode and on hovering a edit icon gets displayed. Onclick of this edit icon the readonly view should now be replaced with edit view. What would be a best approach to achieve this. Below are few options I am considering
- Have a single PrescriptionView with the edit icon and all the form fields required for the edit mode in it. It will also have the logic to change the view from readonly mode to edit mode based on edit trigger.
- Have two views PrescriptionReadView and PrescriptionEditView. The ReadView will have the edit icon and onclick replace the readview with editview.
I am inclined towards #2 but not sure how to implement it in a elegant way. Any thoughts on this will be helpful.
Answered By: Anonymous
Your life will be considerably less painful, if you separate your pretty view from your edit view, since they are, for all intents and purposes, two distinct views of the same data, with different event-handling needs and different behavior. So, your instincts that lead you towards #2 are right on the money.
The cleanest implementation I can think of is to make a container view (say, PrescriptionView) that can handle the mode-swapping events. The container will own a reference to the currently active prescription view, and will handle the creation of that view, and the cleanup (remove and unbind) of the inactive view. That keeps all of that logic nice and self-contained.