Best Practices - tsgrp/HPI GitHub Wiki
##Favorite Modules
Some examples you can look to as good examples of the current best practices:
- savedsearch.js
- startworkflow.js (no knockout)
- completetask.js (knockout)
##Views
###Rendering and Knockout If you are using knockout, you need to becareful about how your view renders. Because we apply bindings in the afterRender, if you render twice you will double apply bindings (bad). You also need to consider if a subview uses knockout, if that's the case, you can only render once....(rendering a parent re-renders the children) More... Moral: don't use knockout
###Never render() in the initialize method. The parent view that creates the view should render the child
var newView = new MyView();
this.setView('#element', newView);
newView.render()
Otherwise you can re-render a view from the helper functions on the view
MyView = Backbone.Layout.extended({
template :....
events: {
...
},
initialize: function(){
...
},
userClickedSomething : function(){
//do work
this.render(); //re-render is ok
}
});
###Always use the scoped jquery selector in views
this.$('#someElement')....
###Events
- Use this.listenTo() when ever possible where 'this' is a view. Having views listen to events ensures cleanup when the view is removed from the DOM (when user navigates away from view)
- If you have to manually register events using jquery, make sure you clean them when the view is removed. This can be done with the built in cleanup method
MyView = Backbone.Layout.extended({
template :....
events: {
...
},
initialize: function(){
...
},
cleanup : function(){
//cleanup logic here
$('window').off();
}
});