-
Notifications
You must be signed in to change notification settings - Fork 305
Backbone styles and tips
Jamie Alexandre edited this page Aug 30, 2014
·
3 revisions
- Views encapsulate a portion of the DOM, and handle all user interactions with that part of the DOM. Be sure to scope any jQuery references to the current view (
this.$(".have-some-class")
orthis.$el.html("...")
) to avoid cross-view interference. - Models serve as the canonical representation of state. Avoid storing app state in the DOM, in the view itself, or in global variables. State lives in the models, and views listen to the models to update the DOM when the state they care about changes. Similarly, when a user interaction needs to change state, it should do so by setting a value on a model. Other views can then respond to the state change as needed.
- Refresh as little of the DOM as possible when state changes, within pragmatic reason. No need to redraw a large complex template if adding/removing a class, or changing some text, will suffice.
- Use
listenTo
anytime you want to bind a view to an event. That way, when you later runmy_view.remove()
, the view is not only removed from the DOM, it also has its listeners unbound to avoid "phantom listeners" later. - Some models encapsulate persistent state (e.g. a log record that is saved to the server), while others represent temporary state to do with the user's current interactions with the interface. It's best to keep this in separate models.
- Views can have subviews. For now, we generally just keep track of these subviews as an attribute on the parent view, or as a list of views as an attribute on the parent view (if there are many of the same type). This way, we can loop over them later, e.g. to "remove" them and thereby clear their event listeners.
- Name a View class ending with
View
(e.g.ExercisePracticeView
). Name a Model ending withModel
(e.g.ExerciseDataModel
). Name a Collection ending withCollection
(e.g.AttemptLogCollection
). - End a View's
render
method with areturn this
, so that the view can be rendered and inserted into the DOM in a single line. - Attach View, Model, and Collection definitions directly to the window object, as it helps to explicitly show that they're in the global namespace (e.g.
window.CurrentUnitRowView = Backbone.View.extend({...
).