0

Can someone explain lang.hitch() function use in ArcGIS API for JavaScript?

2
  • Do you want a demo code or just an explanation?
    – Yogi
    Jan 11 '21 at 18:26
  • @Yogesh Chavan - A demo code would be great help, thanks. Jan 11 '21 at 19:10
3
require(["dojo/_base/lang"], function(lang){
   
    var myObj = { //A simple object with the property of foo
      foo: "bar"
    };
  
    var func = lang.hitch(myObj, function(){ //Using lang.hitch we can point to the scope that we want. Now "this" is pointing to myObj
      console.log(this.foo);//Grabbing the contents of foo that is in a different scope
    });
  
    func(); //Call the function printing out this.foo
  });

In the code above we have a simple myObj object with a property of foo. That object is in a different scope than the function below it. When we call our function called func, we add lang.hitch and specify the scope which is myObj. This allows us to grab the contents of foo even though it is in a different scope by calling this.foo.

If we did not have the lang.hitch we would get an error saying the foo was undefined.

For more info dojo/_base/lang

4
  • As I understand, please correct if I am wrong, using lang.hitch() we can use object properties and functions in different scope or function. Jan 12 '21 at 8:57
  • Yes, that's the main use of the old dojo lang function. In new Code and using the new ArcGIS-JS-API4.x you do not need it anymore since you can use ES6 and array functions.
    – Katah
    Jan 12 '21 at 10:21
  • @Katah- Please can you provide link of any example to understand it for ArcGIS-JS-API4.x. Jan 12 '21 at 14:08
  • Unfortunately I cannot format code in a comment. You can find information here: jsrocks.org/2014/10/arrow-functions-and-their-scope in the chapter "Scope" Anyway, if you go to the Esri documentation developers.arcgis.com/javascript/latest/sample-code you can find nice samples about that
    – Katah
    Feb 17 '21 at 14:57
2

Robert Scheitlin answered a similar question on https://community.esri.com/t5/arcgis-web-appbuilder-questions/lang-hitch-what-does-it-do/m-p/436487

lang.hitch enables you to keep a code block in scope. Say you have a function that has a inline function and you want to call this.map to get a refernec to the map object well if you are calling this.map from inside an inline function you are VERY like to see the error that this.map is undefined. Using lang.hitch before you call your inline function tell the inline function what 'this' is.

https://dojotoolkit.org/reference-guide/1.10/dojo/_base/lang.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.