dojo Quick Start/dojo入门手册dojo.hitch scope/context

既然用到了xmlhttp,一个常见的问题就是回调函数的scope/context。在prototype、mootools里我们常用Function.bind,在dojo中,做相同事情的东西叫做dojo.hitch。

var handler = {
    name:'Mark',
    execute1: function(){
        dojo.xhrGet({
            url: "http://localhost/hello/sayHello.jsp",
            handleAs: "text",
            error: function(text)
            {
                console.dir(this);
                alert(this.name);//输出undefined,这里的this表示当前io参数
            }
            //...
        });
    },
    load: function(text){
        alert(this.name);
    },
    execute2: function(){
        dojo.xhrGet({
            url: "http://localhost/hello/sayHello.jsp",
            handleAs: "text",
            error: dojo.hitch(this,"load") //输出Mark
            //error: dojo.hitch(this,this.load); //与上一句相同,知道为什么要用方法名字而不是引用了吧?省去了长长的一串this.xxx
            //...
        });
    }
}

OK,基本的东西解决了,还有很多常用的函数没有介绍,比如:dojo.query,dojo.forEach,dojo.marginBox,dojo.contentBox等等。这个就没事翻翻dojo.js.uncompressed.js源代码,dojo的文档是没啥好指望的了。

原文地址:https://www.cnblogs.com/soundcode/p/2117556.html