From 60afc9e1ea9d18f4406f79905460f3e89bf58607 Mon Sep 17 00:00:00 2001 From: Maira Bello Date: Thu, 15 Dec 2016 15:26:39 -0800 Subject: [PATCH] Passes original dom event object to beforeNavigate payload --- src/app/App.js | 6 ++++-- test/app/App.js | 26 ++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/app/App.js b/src/app/App.js index 6698331..a4f49c6 100644 --- a/src/app/App.js +++ b/src/app/App.js @@ -627,7 +627,7 @@ class App extends EventEmitter { var navigateFailed = false; try { - this.navigate(utils.getUrlPath(href)); + this.navigate(utils.getUrlPath(href), false, event); } catch (err) { // Do not prevent link navigation in case some synchronous error occurs navigateFailed = true; @@ -665,9 +665,10 @@ class App extends EventEmitter { * Navigates to the specified path if there is a route handler that matches. * @param {!string} path Path to navigate containing the base path. * @param {boolean=} opt_replaceHistory Replaces browser history. + * @param {Event=} event Optional event object that triggered the navigation. * @return {CancellablePromise} Returns a pending request cancellable promise. */ - navigate(path, opt_replaceHistory) { + navigate(path, opt_replaceHistory, opt_event) { if (!utils.isHtml5HistorySupported()) { throw new Error('HTML5 History is not supported. Senna will not intercept navigation.'); } @@ -679,6 +680,7 @@ class App extends EventEmitter { } this.emit('beforeNavigate', { + event: opt_event, path: path, replaceHistory: !!opt_replaceHistory }); diff --git a/test/app/App.js b/test/app/App.js index 8041fe5..ee35607 100644 --- a/test/app/App.js +++ b/test/app/App.js @@ -743,6 +743,32 @@ describe('App', function() { exitDocumentLinkElement(); }); + it('should pass original event object to "beforeNavigate" when a link is clicked', () => { + this.app = new App(); + this.app.addRoutes(new Route('/path', Screen)); + this.app.on('beforeNavigate', (data) => { + assert.ok(data.event); + assert.equal('click', data.event.type); + }); + dom.triggerEvent(enterDocumentLinkElement('/path'), 'click'); + exitDocumentLinkElement(); + + assert.notEqual('/path', window.location.pathname); + }); + + it('should prevent navigation on both senna and the browser via beforeNavigate', () => { + this.app = new App(); + this.app.addRoutes(new Route('/preventedPath', Screen)); + this.app.on('beforeNavigate', (data, event) => { + data.event.preventDefault(); + event.preventDefault(); + }); + dom.triggerEvent(enterDocumentLinkElement('/preventedPath'), 'click'); + exitDocumentLinkElement(); + + assert.notEqual('/preventedPath', window.location.pathname); + }); + it('should not navigate when clicking on external links', () => { var link = enterDocumentLinkElement('http://sennajs.com'); this.app = new App();