简体   繁体   中英

Backbone.js - Is there a way to determine if a route event was triggered on page load

I am using backbone.js and I am in a situation where I need to know if the router event triggered was on page load or if it was triggered by a user clicking. Is there any way to know this within the router action?

I don't think there is a way to distinguish these events. Backbone's History implementation watches changes in the current browser window's URL and can't distinguish how the URL was changed. You most likely will need to roll your own solution (eg checking the entries in the history or use an additional handler on user clicks).

If you want to distinguish your explicit calls to router.route you can pass a custom string as the second parameter which will trigger an event 'route:yourNameHere' , see Backbone's documentation .

You could also set a variable on page load aka somewhere where you initialize your app (say the initialize method of your router)

var Workspace = Backbone.Router.extend({
    initialize: function() {
         var this.pageLoad = true;
     ...

and set it to false on navigating somewhere. You can listen to the route events as described in Julians answer or simply add a line of code like this:

Workspace.pageLoad = false

to your route functions. You could also create a middleman function to handle setting the variable and then calling the respective routes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM