Skip to content

Instantly share code, notes, and snippets.

@tphdev
Created February 27, 2017 18:23
Show Gist options
  • Save tphdev/b718ab8bfab63a1ea80ad31e54733a21 to your computer and use it in GitHub Desktop.
Save tphdev/b718ab8bfab63a1ea80ad31e54733a21 to your computer and use it in GitHub Desktop.
router.js - undelegating events
const AppRouter = Backbone.Router.extend({
//(1)
_currentViewInstance: null,
//(2a) this will undelegate the event-listeners
// from the 'zombie view'
_destroyZombieView: function(){
console.log(this._currentViewInstance)
if(this._currentViewInstance !== null) {
this._currentViewInstance.undelegateEvents();
}
},
initialize: function(){
Backbone.history.start()
},
routes: {
"item/:id" : "showSingleItem",
"new" : "showNewItemForm",
"" : "showListings"
},
showSingleItem: function(idVal){
this._destroyZombieView();
let mod = new ItemModel()
mod.set({_id: idVal })
let router = this
mod.fetch().then(function(){
router._currentViewInstance = new SingleView()
router._currentViewInstance.render(mod)
})
},
showNewItemForm: function(){
// (2b) method is invoked on each route. will
// destroy the events assigned to the DOM
// that were from the previous view
this._destroyZombieView()
// (3) set the router's current view instance
// with the view instance that renders for
// this route. this will allow us to clear it
// the next time the user navigates and
// another route-method is triggered
this._currentViewInstance = new NewItemFormView()
this._currentViewInstance.render()
},
showListings: function(){
this._destroyZombieView()
let coll = new ItemCollection()
// (NOTE): We have to do the router = this trick
// because the `this` keyword is not
// binded to the original router's context
// inside of the .then() callback function.
let router = this
coll.fetch().then(function(){
router._currentViewInstance = new HomeView()
router._currentViewInstance.render(coll)
})
},
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment