2016-10-28 131 views
0

我沒有在文檔中找到如何從嵌套的require塊中訪問類的方法的局部變量。在嵌套的require塊中訪問局部變量/方法?

declare("Clust", StrictIntHashMap, 
    {  
     constructor : function() 
     { 

     }, 

     cust : function(custId) 
     { 
      return this.get(custId); 
     }, 

     add : function(custObject) 
     { 
      this.set(custObject.custId, custObject); 
     }, 

     reloadThecustses : function() 
     { 
      that = this; 
      require([ 'inst/DataExtractor', 'inst/ClustTree' ], function (de, theTree) 
      { 

       de.getPlainJSON(Commandz.COMMAND_GET_CUSTS, 
       function (dataR) 
       { 
        that.add(new Customer(dataR.root[c])); // not working 
        this.cust(0); // not working 

        theTree.refreshTheData(dataR.root); 

       }); 

      }); 
     } 


    });  

    return Clust; 
  • 如何訪問該方法從需要塊內的類的「添加」?
  • 如何從require塊中訪問本地變量「that」?
+0

你運行什麼確切的測試代碼來聲明它「不工作」? – Louis

+0

Custs.js:60 Uncaught ReferenceError:沒有定義,如果我刪除它並將其替換爲「this.add(whatever)」,它會變爲「Custs.js:61 Uncaught TypeError:無法讀取屬性'add'undefined 「 –

+1

但是''''是在你的代碼中定義的。你用'that = this'來定義它。你應該真的有'var that = this',因爲如果沒有'var',你把它放在全局空間中,這是不好的編碼,但它*是*定義的。 – Louis

回答

1

當使用require時,您應該能夠訪問在父範圍中定義的變量,因爲它相當於只具有子範圍。

我不完全確定你想要訪問什麼,但我認爲它是Clust實例。

請問這段代碼適合你嗎?

declare("Clust", StrictIntHashMap, {  
    constructor : function() { 
    }, 
    cust : function(custId) { 
     return this.get(custId); 
    }, 
    add : function(custObject) { 
     this.set(custObject.custId, custObject); 
    }, 
    reloadThecustses : function() { 
     var clustInstance = this; 
     require([ 'inst/DataExtractor', 'inst/ClustTree' ], 
     function (de, theTree) { 
     de.getPlainJSON(Commandz.COMMAND_GET_CUSTS, function (dataR) { 
      clustInstance.add(new Customer(dataR.root[c])); 
      clustInstance.cust(0); 
      theTree.refreshTheData(dataR.root); 
     }); 
    }); 
    } 
});  

return Clust; 
1

也許問題是由回調函數中的錯誤上下文導致getPlainJSONdojo.hitch()將修復此問題:

reloadThecustses : function() 
    { 
     require([ 'inst/DataExtractor', 'inst/ClustTree', 'dojo/_base/lang' ], function (de, theTree, lang) 
     { 
      de.getPlainJSON(Commandz.COMMAND_GET_CUSTS, 
      lang.hitch(function (dataR) 
      { 
       this.add(new Customer(dataR.root[c])); // not working 
       this.cust(0); // not working 

       theTree.refreshTheData(dataR.root); 

      }, this) 
     }); 
    }