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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…