How to detect invalid route and trigger function i

2020-02-12 04:47发布

问题:

Is there any method to detect invalid (or undefined) route and trigger 404 page in Backbone.Controller?

I've defined routes in my Controller like this, but it didn't work.

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"

UPDATE:

I used constructor of Backbone.Controller to match current hash fragment and @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:

The above works, but I'm not sure why you have to do what you do in the constructor. It may be slightly brittle, but we create a separate controller that we include in last. Its last so that the splat route is the last one to match:

NotFound = Backbone.Controller.extend({

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

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

});

new NotFound();

Using a more robust version of the above seems a cleaner approach to me.