在不同视图中使用模型属性值

时间:2013-11-09 11:42:18

标签: jquery backbone.js requirejs

我是骨干的新手,并尝试弄清楚如何在我的单页应用程序上传递模型属性。 我正在使用带有jquery,requirejs和下划线的骨干。

我的代码看起来像 模型:

    define([
    'jquery',
    'underscore',
    'backbone'
], function ($, _, Backbone) {

    'use strict';

    var sessionCall = Backbone.Model.extend({

        url: "http://myserver/sessionCall",

        defaults: {
            APIKey: 'NULL'
        },

        initialize: function() {

            $.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
                options.crossDomain ={
                    crossDomain: true
                };
                options.xhrFields = {
                    withCredentials: false
                };
            });
            return this;
        }
    });

    return sessionCall;
    });

登录视图:

 define([
    'jquery',
    'underscore',
    'backbone',
    'router',
    'models/mSessionCall',
    'text!tpl/login.html'
], function ($, _, Backbone, AppRouter model, tpl) {

   // var loginView = Backbone.View.extend({ //if used //return loginView; below

    return Backbone.View.extend({

        events: {
            "click #clb_login":         "callLoginCheck",
            "click #clb_newAccount":    "callNewAccount"
        },

        initialize: function () {

        },

        el: $('#container'),
        render: function () {

            var template = _.template(tpl);
            this.$el.html(template());
        },

        callLoginCheck: function (e) {
            e.preventDefault(); //Don't let this button submit the form

            var loginCheck = new model();
            //Save working version
            loginCheck.save( {
                success: function (loginCheck, data) {
                    loginCheck.set({USR_APIKey: data[0]['USR_APIKey']});
                    appRouter.navigate('home', true);
                },
                error: function(loginCheck, response) {
                    console.log('error');
                    appRouter.navigate('', true);
                }
            });
        },

        callNewAccount: function () {
            appRouter.navigate('newAccount', true);
        }
    });
});

主页视图:

最重要的是工作完美。但是如何在不同的视图中使用我的USR_APIKey,因为我需要此密钥才能在我的REST服务器上更新/获取/删除我的日期。

有什么想法吗? thx

2 个答案:

答案 0 :(得分:0)

我认为最好的方法是在某些地方(会话或其他地方)保存api密钥,因为如果你想获得这个值,你必须每次创建一个登录vieew并以这种方式获得这个属性,例如: / p>

this.loginView = new LoginView();
this.loginView.model.get('APIKey');

答案 1 :(得分:0)

从浏览器的角度来看,我们有两个熟悉的事情。

  • 的sessionStorage
  • localStorage的

您可以使用上述任何一项来存储USR_APIKey的值。

否则,每次需要USR_APIKey值时都必须调用LoginView(),这不是一个好习惯(在性能方面)。而且为了摆脱僵尸视图,我们在UI范围结束时关闭每个视图。

希望这有帮助