嗨,我已经花了几天时间尝试研究backbone.js,但由于这是我的第一个 MVC 框架,所以很难。
我可以轻松地让我的集合工作,从服务器获取数据等,但这一切都取决于每个 API key 的第一次“登录”。我只是不知道如何使用良好的 MVC 方法对此进行建模。 (顺便说一句:我无法使用路由器/ Controller ,因为它是 Chrome 扩展)
流程如下所示:
- 启动扩展
- localStorage 中是否有 API key ?
- 否 => 显示一个输入字段和一个将 key 保存到 localStorage 的保存按钮; 是 => 继续申请:
- 应用......
我能想到的唯一方法是将它们放在一个大 View 中......但我想由于我对此相当陌生,肯定有一些更好的方法。
最佳答案
您可以创建一个维护用户登录状态的模型和一个根据该状态呈现不同模板的 View 。如果用户未登录,则该 View 可以显示“输入字段”模板;如果用户已登录,则该 View 可以显示不同的模板。我将保留对模型中 localStorage 的所有访问,因为 View 不应该关心持久性。该 View 可能也不应该关心 API key ,这就是为什么我将 View 绑定(bind)到模型的登录更改('change:loggedIn')而不是 apiKey 更改......尽管我在一个中显示 API key 我的模板仅用于演示目的。这是我非常简化的示例。请注意,我没有费心验证 API key ,但您可能需要:
模板:
<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>
主干模型和 View :
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);
关于javascript - Backbone.js - 如何处理 "login"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7220020/