javascript Backbone.js - 如何处理“登录”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7220020/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:21:05  来源:igfitidea点击:

Backbone.js - how to handle "login"?

javascriptbackbone.js

提问by algorithms

Hi I'm trying to wrap my head around backbone.js for some days now but since this is my first MVC Framework, it's pretty hard.

嗨,我想围绕着backbone.js 转了几天,但因为这是我的第一个MVC 框架,所以很难。

I can easily get my Collections to work, fetching data from the server etc, but it all depends on first "logging" in per API-Key. I just don't know how to model this with a good MVC approach. (btw: I can't use the Router/Controller because it's a Chrome Extension)

我可以轻松地让我的集合工作,从服务器等获取数据,但这一切都取决于每个 API 密钥的第一个“登录”。我只是不知道如何使用良好的 MVC 方法对此进行建模。(顺便说一句:我不能使用路由器/控制器,因为它是一个 Chrome 扩展)

The Flow looks like this:

流程如下所示:

  1. StartExtension
  2. Is there an API-Keyin localStorage?
  3. No=> Display a input field and a save button which saves the key to localStorage; Yes=> proceed with the Application:
  4. App......
  1. 开始扩展
  2. localStorage 中有API-Key吗?
  3. => 显示一个输入字段和一个将密钥保存到 localStorage 的保存按钮;=> 继续申请:
  4. 应用程序......

The only way I could think of it is putting it all together in a big View... but I guess since I am fairly new to this there are surely some better approaches.

我能想到的唯一方法是将它们放在一个大视图中......但我想因为我对此相当陌生,所以肯定有一些更好的方法。

回答by Johnny Oshika

You can create a model that maintains the state of the user's login status and a view that renders a different template depending on that status. The view can show the "input field" template if the user is not logged in and a different template if the user is. I would keep all access to localStorage in the Model because the View should not be concerned with persistence. The view should probably not be concerned with the API Key as well, and that's why I have my view binding to the model's loggedIn change ('change:loggedIn') instead of apiKey change...although I am showing the API key in one of my templates for demonstration purpose only. Here's my very simplified sample. Note that I didn't bother with validating the API Key, but you'll probably want to:

您可以创建一个模型来维护用户登录状态的状态,以及一个根据该状态呈现不同模板的视图。如果用户未登录,则视图可以显示“输入字段”模板,如果用户已登录,则显示不同的模板。我会在模型中保留对 localStorage 的所有访问权限,因为视图不应该关心持久性。视图可能也不应该关注 API 密钥,这就是为什么我将视图绑定到模型的登录更改 ('change:loggedIn') 而不是 apiKey 更改......尽管我将 API 密钥显示在一个我的模板仅用于演示目的。这是我非常简化的示例。请注意,我没有费心验证 API 密钥,但您可能想要:

Templates:

模板:

<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>

Backbone Model and 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);