Extend Backbone View with mixin
In several cases you need to provide the same functions inside your views that do the exact thing. For example the already implemented (but empty) render()
. You might also need your special ones like show()
, hide()
, bindKeys()
, setHeader()
, etc..
One solution can be the following: create a plain js object with methods you want to share between views,
Device = {
/* ... */
Navigation:{
/* ... */
methods:{
fire:function (/* ... */) {
/* ... */
},
rebindKeys:function () {
/* ... */
},
bindKeys :function () {
/* ... */
},
unbindKeys:function () {
/* ... */
}
}
}};
then instead of define your view object with SearchView = Backbone.View.extend(
, use the following syntax:
SearchView = Backbone.View.extend(
_.extend({}, Device.Navigation.methods, {
el :'#viewSearch',
events :{
/* ... */
Now after instantiate a view app.searchView = new SearchView();
, you can call app.searchView.bindKeys()
or whatever you attached to your view.
If you call a shared method while instantiate a view, don’t forget to close that method with a return this;
line.
/* ... */
show:function () {
this.unbindKeys();
this.bindKeys();
return this;
},
/* ... */
Hope you like it :)