javascript - Backbone: abort previous router callback execution -
suppose have 2 links on page:
<a href="#a">link a</a> <a href="#b">link b</a>
and use backbone router handle in-app page navigation.
on routing link '#a', have registered listenera , listenerb '#b' both listenera , listenerb heavy task in background.
now, let's user clicks 'link a' , gap of few milliseconds, clicks 'link b'.
so, happens when listenera done execution, listenerb starts executing due single ui thread.
is there way, can block/abort/preempt execution of listenera if listenerb requested?
it's expected user see response latest action. previous actions should not honored if 2 actions similar.
to understand how backbone handles routes lets review chunk of code backbone.history
:
if (this._haspushstate) { backbone.$(window).on('popstate', this.checkurl); } else if (this._wantshashchange && ('onhashchange' in window) && !oldie) { backbone.$(window).on('hashchange', this.checkurl); } else if (this._wantshashchange) { this._checkurlinterval = setinterval(this.checkurl, this.interval); }
if using modern browser 2nd if black subscribe hashchange
event , time navigate link link call checkurl
manage call appropriate action.
so direct answer queastion no, can't.
but can use few workarounds depending doing in actions.
1st solution.
use settimeout()
or similar _.debounce()
function. select links need protected or single treathed , navigate needed url mnually:
$(document.body).on('click', 'a:not([reference-to-out])', function(e){ e.preventdefault(); if (app.linktimeoutid) { cleartimout(app.linktimeoutid); } app.linktimeoutid = settimeout(function () { app.linktimeoutid = null; app.router.navigate(e.currenttarget.pathname, {trigger: true}); }, 500) });
2nd solution
if heavy tasks network related (fetching collection, doing requests remote), track them keeping in object , cancel them when backbone.router fires 'route' event. prevent lot of needless operations.
3rd solution
i thinking $.deferred
objects, in case should wrap controller's actions , keep track of them.
Comments
Post a Comment