2011-08-28 14 views
23

こんにちは私はいくつかの日のbackbone.jsの周りを頭で囲んでいますが、これは私の最初のMVCフレームワークなのでかなり難しいです。Backbone.js - 「ログイン」の扱い方は?

私のコレクションは簡単に機能し、サーバーなどからデータを取得できますが、APIキーごとの最初の「ログ」に依存します。私はちょうど良いMVCのアプローチでこれをモデル化する方法を知らない。

  1. スタート拡張
  2. APIキーがあります:

    フローは次のようになります(ところで、それはクローム拡張だから、私は、ルータ/コントローラを使用することはできません) localstorageの

  3. いいえ =>入力フィールドとそのキーをlocalStorageに保存する保存ボタンを表示します。 はい =>アプリケーションを続行:私はそれを考えることができる唯一の方法は、大きなビューで一緒にそれをすべて入れている

......

  • のApp ...しかし、私私はこれにかなり新しいですから、確かに良いアプローチがいくつかあります。

  • 答えて

    48

    ユーザーのログイン状態の状態を維持するモデルと、その状態に応じて別のテンプレートをレンダリングするビューを作成できます。ビューには、ユーザーがログインしていない場合は「入力フィールド」テンプレート、ユーザーがいる場合は別のテンプレートが表示されます。ビューは永続性に関係してはならないので、私はモデルにlocalStorageへのすべてのアクセスを維持します。ビューはおそらくAPIキーにも関与しないはずです。そのため、apiKeyの変更ではなく、モデルのloggedInの変更( 'change:loggedIn')にバインドされたビューを持っていますデモ目的のためだけに私のテンプレートの。ここに私の非常に単純化されたサンプルがあります。私はAPIキーの検証を気にしなかったことに注意してください、しかし、あなたはおそらくしたいと思う:

    テンプレート:

    <script id="logged_in" type="text/html"> 
        You're logged in. Your API key is <%= escape('apiKey') %>. Let's proceed with the application... 
    </script> 
    <script id="not_logged_in" type="text/html"> 
        <form class="api_key"> 
         API Key: <input name="api_key" type="text" value="" /> 
         <button type="sumit">Submit</button> 
        </form> 
    </script> 
    

    基幹モデルとビュー:

    var LoginStatus = Backbone.Model.extend({ 
    
        defaults: { 
         loggedIn: false, 
         apiKey: null 
        }, 
    
        initialize: function() { 
         this.bind('change:apiKey', this.onApiKeyChange, this); 
         this.set({'apiKey': localStorage.getItem('apiKey')}); 
        }, 
    
        onApiKeyChange: function (status, apiKey) { 
         this.set({'loggedIn': !!apiKey}); 
        }, 
    
        setApiKey: function(apiKey) { 
         localStorage.setItem('apiKey', apiKey) 
         this.set({'apiKey': apiKey}); 
        } 
    
    }); 
    
    var AppView = Backbone.View.extend({ 
    
        _loggedInTemplate: _.template($('#logged_in').html()), 
        _notLoggedInTemplate: _.template($('#not_logged_in').html()), 
    
        initialize: function() { 
         this.model.bind('change:loggedIn', this.render, this); 
        }, 
    
        events: { 
         'submit .api_key': 'onApiKeySubmit' 
        }, 
    
        onApiKeySubmit: function(e){ 
         e.preventDefault(); 
         this.model.setApiKey(this.$('input[name=api_key]').val()); 
        }, 
    
        render: function() { 
         if (this.model.get('loggedIn')) { 
          $(this.el).empty().html(this._loggedInTemplate(this.model)); 
         } else { 
          $(this.el).empty().html(this._notLoggedInTemplate(this.model)); 
         } 
         return this; 
        } 
    }); 
    
    var view = new AppView({model: new LoginStatus()}); 
    $('body').append(view.render().el); 
    
    +0

    良い1ジョニーを! –