【问题标题】:assigning a variable inside the getJSON function在 getJSON 函数中分配一个变量
【发布时间】:2013-12-04 21:44:17
【问题描述】:

在 Backbone & marionette 中,我使用 json 来获取我的翻译。我在 onBeforeRender 函数下的 ItemView 中执行此操作。但是每当我调用“this.model.set”函数时,我总是会收到错误消息“TypeError:this.model is undefined”。有没有办法将 getJSON 之外的变量设置为在 getJSON 函数内部分配?

  onBeforeRender: function(model){

        //let's get the json translation file before we render the view 
        var jqXHR = $.getJSON("en.json", function(data, textStatus, jqXHR) {
            this.model.set({trans:jqXHR.responseJSON}); //it fails here

            return jqXHR.responseJSON;


        }).fail(function(data){

        }).then(function(data){

        }).done(function(data){
            console.debug(data)
        });

    },

或者,如果有人对如何更好地做到这一点提出建议,那就太好了。

【问题讨论】:

    标签: javascript json backbone.js marionette


    【解决方案1】:

    this 可能不是指您认为的那样。设置一些上下文并重试:

    var that = this;
    //let's get the json translation file before we render the view 
     var jqXHR = $.getJSON("en.json", function(data, textStatus, jqXHR) {
        that.model.set({trans:jqXHR.responseJSON}); //it fails here
    
        return jqXHR.responseJSON;
    

    【讨论】:

      【解决方案2】:

      .getJSON 回调中的 this 不是您想的那样。使用以下代码:

      var self = this;
      var jqXHR = $.getJSON("en.json", function(data, textStatus, jqXHR) {
          self.model.set({trans:jqXHR.responseJSON}); //it fails here
          return jqXHR.responseJSON;
      }).fail(function(data){
      
      }).then(function(data){
      
      }).done(function(data){
          console.debug(data)
      });
      

      在您的代码中,this 指向回调而不是视图。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-14
        • 1970-01-01
        • 2015-10-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-23
        相关资源
        最近更新 更多