2011-06-27 22 views
8

有沒有什麼方法可以檢測Backbone.Controller中的無效(或未定義)路由和觸發404頁面?如何檢測Backbone.Controller中的無效路由和觸發器功能

我在我的控制器中定義了這樣的路由,但它沒有工作。

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:

我用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" 
+0

如果你已經解決了你自己的問題,然後回答你自己的問題。 – Raynos

+2

建議是重寫您的問題,以便它只包含問題,然後提供您自己的答案。所以,請忽略問題中的答案。如果您沒有立即提供答案,您可能會發現某人有更好的方法來回答您的問題。 –

+0

是的,你的建議是對的。感謝您分享! – tomodian

回答

10

上述工作,但我不知道爲什麼你必須做你在構造函數中做什麼。它可能稍微脆弱一點,但是我們創建了一個單獨的控制器,我們最後包含它。其最後運行,這樣的圖示路線是最後一個匹配:

NotFound = Backbone.Controller.extend({ 

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

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

}); 

new NotFound(); 

使用上述一個更強大的版本似乎更清潔的方式給我。

+0

我是骨幹新手,並希望使用Rails before_filter類似的方法,它會在運行Controller的方法之前觸發。但是你的解決方案似乎也很健壯和清潔。謝謝! – tomodian