簡體   English   中英

在getJSON函數中分配變量

[英]assigning a variable inside the getJSON function

在Backbone&marionette中,我使用json來獲取翻譯。 我在onBeforeRender函數下的ItemView中執行此操作。 但是,每當我調用“ this.model.set”函數時,總會收到錯誤消息,提示“ TypeError:this.model未定義”。 有沒有辦法設置要在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)
        });

    },

或者,如果有人對如何更好地做到這一點提出建議,那就太好了。

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;

this.getJSON回調是不是你的想法。 使用以下代碼:

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指向回調而不是視圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM