2011-06-27 5 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:

私は現在のハッシュフラグメントと@routesに一致するようにBackbone.Controllerのコンストラクタを使用します。

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

私はBackbone newbieです。コントローラのメソッドを実行する前にトリガするRails before_filterのようなアプローチを使いたかったのです。しかし、あなたのソリューションも堅牢できれいに見えます。ありがとうございました! – tomodian

関連する問題