首页 文章

在getJSON函数中分配变量

提问于
浏览
0

在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)
        });

    },

或者,如果有人有关于如何更好地做到这一点的建议,这将是伟大的 .

2 回答

  • 1

    您的 .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 指向回调而不是视图 .

  • 0

    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;
    

相关问题