您可以創建一個模型來維護用戶登錄狀態的狀態以及根據該狀態呈現不同模板的視圖。該視圖可以顯示「輸入字段」模板,如果用戶未登錄,則顯示不同的模板。我將在模型中保留對localStorage的所有訪問權限,因爲View不應該關注持久性。該視圖可能不應該用的API密鑰被關注爲好,這就是爲什麼我有我的觀點結合到模型的的loggedIn變化(「改變:的loggedIn」),而不是apiKey變化......雖然我顯示在一個API密鑰我的模板僅用於演示目的。這是我非常簡單的示例。請注意,我沒有驗證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);
好一個約翰尼! –