【问题标题】:SessionStorage in backbone doesn't work before refresh page主干中的 SessionStorage 在刷新页面之前不起作用
【发布时间】:2014-05-09 11:07:27
【问题描述】:

我现在正在开发一个主干应用程序,我认为 sessionStorage 值有问题。如果您认为还有其他问题,请告诉我!

当我运行这个脚本时:

    <script>
      console.log((sessionStorage.appRole == "1" || sessionStorage.appRole == "2"));
    </script>

那么控制台中的结果为真。

但是,当使用 underscorejs 将值用于我的主干中的模板时,IF 语句中的值不会呈现。但是当我刷新我的页面时,按钮是可见的。我想知道为什么我第一次访问该页面时它不起作用。该值是正确的,但它没有被渲染。

    <% if (sessionStorage.appRole == "1" || sessionStorage.appRole == "2") { %>
      <button id="create" class="btn btn-primary"><%= i18n.create_user %></button>
    <% } %>

你有什么想法吗?我已经挠头好几个小时了,现在我请求你的帮助!

【问题讨论】:

    标签: javascript backbone.js session-storage


    【解决方案1】:

    您应该获取值并将其存储到变量中,然后将其传递给模板。 由于模板正在寻找该变量中的值,因此它失败了。

    var appRole = sessionStorage.appRole;
    var user = i18n.create_user;
    

    将 appRole、用户值传递给模板

    $(this.el).html(this.myTemplate({"appRole": appRole,"userDetail":user }));
    

    在模板里面获取它就像

    <% if (appRole == "1" || appRole == "2") { %>
    <button id="create" class="btn btn-primary"><%= userDetail %></button>
    <% } %>
    

    对于 myTemplate ,在视图中包含您的模板并使用下划线模板函数分配它。

    myTemplate : _template(sampleTemplate),
    

    并使用 this.myTemplate(mymodelobj.toJSON());随时随地。

    查看示例视图文件

    define([
         'jquery',
         'underscore',
         'backbone',
         // Using the Require.js text! plugin, we are loaded raw text
         // which will be used as our views primary template
         'text!templates/project/list.html'
       ], function($, _, Backbone, projectListTemplate){
      var ProjectListView = Backbone.View.extend({
          el: $('#container'),
          render: function(){
                  // Using Underscore we can compile our template with data
          var data = {};//json data
          var compiledTemplate = _.template( projectListTemplate, data );
          // Append our compiled template to this Views "el"
          this.$el.append( compiledTemplate );
       }
    });
    

    // 我们的模块现在返回我们的视图 返回项目列表视图; });

    【讨论】:

    • 感谢您的评论,我明天会在@work 试试这个。并回复结果。 :)
    • 我收到一个错误:未捕获的 TypeError: string is not a function $(this.el).html(this.template({ 'appRole': sessionStorage.appRole }));该错误将模板函数定位为字符串而不是函数。
    • 请检查模板的初始化
    • 对不起,我不是骨干大师。你说的是:({ template: _.template(UsersTemplate) }); 或者是在视图的其他地方启动?
    • 是的,完全一样。我已经更新了答案。请验证。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多