UUDigitalHumanitieslab / EDPOP

A virtual research environment (VRE) that lets you collect, align and annotate bibliographical and biographical records from several online catalogs.
BSD 3-Clause "New" or "Revised" License
1 stars 0 forks source link

Render-placement antipattern #131

Open jgonggrijp opened 1 year ago

jgonggrijp commented 1 year ago

After #130, this "gotcha" seems worthwhile to document as well.

The following pattern frequently occurs in snippets of Backbone example code, scattered across the web:

someView.render().$el.appendTo(someTargetElement);

someView.render() returns someView by convention, so the above pattern is equivalent to the following two lines, which by themselves are both perfectly reasonable:

// rendering the view
someView.render();

// placing the view
someView.$el.appendTo(someTargetElement);

The single-line version, where rendering and placing the view happen in one go, frequently appears in example code because it is a convenient, simple way to demonstrate features of the library. However, it is a form of code smell when encountered in production code. (Side note: other libraries have similar problems with example code that should not be imitated too literally.) While it is safe to combine the operations, they generally happen for very different reasons, which tend to be separated both in execution time and code space, so seeing them in the same place is a likely indicator of improper state management.

Rendering a view happens in order to align its contents with whatever it is meant to present. It only affects the internal structure of the view's DOM element. For this reason, it is generally also the responsibility of the view to decide when it will render itself, for example when the underlying model changes. This can be done regardless of whether the view is visible to the user at that time. The initialize method of a view commonly contains this.render() and/or something like this.listenTo(this.model, 'change', this.render). In fact, the only reason not to self-render a view on creation is when rendering is too expensive, but this in itself is a situation that should be avoided when possible.

Placing a view happens in order to integrate it in a larger context and make it visible to the user. This never affects the view's internal structure and the view itself generally has not enough information to decide where it should be placed, or when. One could say that placement is the external complement to rendering.