Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
451 views
in Technique[技术] by (71.8m points)

backbone.js - How to detect invalid route and trigger function in Backbone.Controller

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...