如何在Backbone.Controller中检测无效路由和触发器功能

时间:2011-06-27 06:01:59

标签: backbone.js coffeescript

是否有任何方法可以在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"

1 个答案:

答案 0 :(得分:10)

以上是有效的,但我不确定你为什么要在构造函数中做你做的事情。它可能稍微脆,但我们创建了一个单独的控制器,我们在最后包含。它的最后一个是splat路由是最后一个匹配:

NotFound = Backbone.Controller.extend({

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

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

});

new NotFound();

使用更强大的上述版本对我来说似乎更简洁。

相关问题