Hitch ()
Hitch () is a function that executes a given execution function at the given top and bottom. Hitch allows you to control how a function executes and often works in an asynchronous operation.
We often write code like this: (blogger: This code intends to execute the "processevent" definition at this point when the "click" event is triggered.) )
1 function (ON) {2 var function (e) {3 this. Something = "Else"; 4 }; 5 On (Something, "click", processevent); 6 });
It is an error because of a variable that cannot be resolved. The reason is that, like the scenario for an asynchronous callback function above, the context changes when the code is executing. The execution context is no longer the originally supplied object, and it points to the external object (on the callback function), in order to solve this problem, you can use Hitch () to force the processevent at this point in the "this" point to the context to execute. as follows:
1 require (["dojo/on", "Dojo/_base/lang"], function 2 3 var processevent = function 4 this . Something = "Else" 5 }; 6 7 on (Something, "click", Lang.hitch ( Span style= "color: #0000ff;" >this , processevent)); 8 9 });
(bloggers, this problem caused by the change in the execution context, can be resolved with hitch (), when using this, be aware of whether the analysis will occur due to the execution of context changes, and error . )
Example:
A simple example:
1Require (["Dojo/_base/lang"],function(lang) {2 varMYOBJ = {3Foo: "Bar"4 };5 6 varFunc = Lang.hitch (MYOBJ,function(){7Console.log ( This. foo);8 });9 Ten func (); One});
The bar will be printed successfully. So when the function Console.log (this.foo) is executed, this points to myobj.
when calling a function that is a method of a given execution context , you can use the method to kill the arguments, as follows:
1Require (["Dojo/_base/lang"],function(lang) {2 varMYOBJ = {3Foo: "Bar",4Methodfunction(somearg) {5Console.log ( This. foo);6 }7 };8 9 varFunc = Lang.hitch (MYOBJ, "method");Ten One func (); A});
At the same time, the function executes if the parameter is required , as follows:
1Require (["Dojo/_base/lang"],function(lang) {2 varMYOBJ = {3Foo: "Bar",4Methodfunction(somearg) {5Console.log (Somearg + "" + This. foo);6 }7 };8 9 varFunc = Lang.hitch (MYOBJ, "method", "Baz");Ten One func (); A});
The above code will print: Baz bar
Dojo Official API translation or Interpretation-dojo/_base/lang--hitch ()