【问题标题】:How to detect invalid route and trigger function in Backbone.Controller如何在 Backbone.Controller 中检测无效路由和触发功能
【发布时间】:2011-09-23 06:23:47
【问题描述】:

是否有任何方法可以检测无效(或未定义)的路由并在 Backbone.Controller 中触发 404 页面?

我已经像这样在我的控制器中定义了路由,但它不起作用。

class MyController extends Backbone.Controller
    routes:
        "method_a": "methodA"
        "method_b": "methodB"
        "*undefined": "show404Error"

    # when access to /#method_a
    methodA: ->
        console.log "this page exists"

    # when access to /#method_b
    methodB: ->
        console.log "this also exists"

    # when access to /#some_invalid_hash_fragment_for_malicious_attack
    show404Error: ->
        console.log "sorry, this page does not exist"

更新:

我使用 Backbone.Controller 的构造函数来匹配当前哈希片段和@routes。

class MyController extends Backbone.Controller
    constructor: ->
        super()
        hash = window.location.hash.replace '#', ''
        if hash
            for k, v of @routes
                if k is hash
                    return
                @show404Error()

    routes:
        "method_a": "methodA"
        "method_b": "methodB"
        "*undefined": "show404Error"

    # when access to /#method_a
    methodA: ->
        console.log "this page exists"

    # when access to /#method_b
    methodB: ->
        console.log "this also exists"

    # when access to /#some_invalid_hash_fragment_for_malicious_attack
    show404Error: ->
        console.log "sorry, this page does not exist"

【问题讨论】:

  • 如果您已经解决了自己的问题,请回答您自己的问题。
  • 建议重写您的问题,使其仅包含问题,然后提供您自己的答案。所以,省略问题中的答案。如果您不立即提供答案,您可能会发现有人有更好的方式来回答您的问题。
  • 是的,你的建议是对的。感谢您分享它!
  • 也不要把解决的放在答案里

标签: backbone.js coffeescript


【解决方案1】:

上述方法有效,但我不确定为什么你必须做你在构造函数中所做的事情。它可能有点脆弱,但我们创建了一个单独的控制器,我们最后将其包含在内。它的最后一个,因此 splat 路线是最后一个匹配的:

NotFound = Backbone.Controller.extend({

  routes: {
    "*path"  : "notFound"
  },

  notFound: function(path) {
    var msg = "Unable to find path: " + path;
    alert(msg);
  }

});

new NotFound();

对我来说,使用上述更强大的版本似乎是一种更清洁的方法。

【讨论】:

  • 我是 Backbone 新手,想使用 Rails before_filter-like 方法,在运行 Controller 的方法之前触发。但是您的解决方案似乎也很强大和更清洁。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 2021-12-04
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
相关资源
最近更新 更多