【发布时间】: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"
【问题讨论】:
-
如果您已经解决了自己的问题,请回答您自己的问题。
-
建议重写您的问题,使其仅包含问题,然后提供您自己的答案。所以,省略问题中的答案。如果您不立即提供答案,您可能会发现有人有更好的方式来回答您的问题。
-
是的,你的建议是对的。感谢您分享它!
-
也不要把解决的放在答案里