Backbone.js 历史“路由更改"事件? [英] Backbone.js history 'on route change' event?

查看:19
本文介绍了Backbone.js 历史“路由更改"事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次导航到不同的 URL 时是否都会触发一个常规事件?

Is there a general event that fires every time we navigate to a different URL?

window.App =
  Models: {}
  Collections: {}
  Views: {}
  Routers: {}

  init: ->
    # Initialize Routers
    new App.Routers.Main()

    # Initialize History
    Backbone.history.start(pushState: true)

    # BIND VIEW CHANGE?
    $(@).on 'changeOfRoute', -> 
      console.log "Different Page" 

$(document).ready ->
  App.init()

可以按视图执行此操作,但我正在寻找通用解决方案.

Doing this per view is possible, but I'm looking for a general solution.

推荐答案

Router上有route"事件:

There is the "route" event on the Router:

http://backbonejs.org/#Events-catalog

  • "route" (router, route, params) — 当任何路由匹配时由历史记录(或路由器)触发.

这允许你绑定到特定的路由.

This allows you to bind to specific routes.

如果你想在任何路由之后触发处理程序,绑定到路由",路由将是第一个参数:

If you want to fire a handler after any route, bind to "route", and the route will be the first argument:

myRouter.on("route", function(route, params) {
    console.log("Different Page: " + route);
});

这只会为您明确定义的路线触发事件.如果要为未明确定义的路由触发事件,请根据 如何检测Backbone.Controller中的无效路由和触发函数

This will only trigger events for your explicitly defined routes. If you want to trigger events for routes that are not explicitly defined, then add a 'splat' route as per How to detect invalid route and trigger function in Backbone.Controller

这篇关于Backbone.js 历史“路由更改"事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆