ユーザーのログイン状態の状態を維持するモデルと、その状態に応じて別のテンプレートをレンダリングするビューを作成できます。ビューには、ユーザーがログインしていない場合は「入力フィールド」テンプレート、ユーザーがいる場合は別のテンプレートが表示されます。ビューは永続性に関係してはならないので、私はモデルに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);
良い1ジョニーを! –