2013-11-09 38 views
0

我是一个新的主干,并试图找出如何在我的单页应用程序上传递模型属性。 我正在使用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

回答

0

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

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

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

  • 的sessionStorage
  • localStorage的

您可以使用上述任何存储USR_APIKey的价值。

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

希望这会有帮助

相关问题