开发者

Need reference to this is dojo widget

dojo.declare("profile.BasicInfo", [dijit._Widget, dijit._Templated], {
  so开发者_运维百科mefunc: function() {
    dojo.xhrPost({
        url: ajaxURL,
        content: adata,
        load: function(data) {
            alert(this);//this refers to the object sent to xhrPost
        }
    });
  },
  somevar: 17
});

the place where I used this refers to the object im sending as parameter to the function xhrPost. This is correct. No errors. But I want to access the object that is the third parameter to dojo.declare.

or I want to access somevar . surely this.somevar wont work.

One possible solution that I came up with is to use a duplicate reference to this and then use it inside xhrPost. Will this work ? Or am I using the Objects in a wrong way. Or will this give problem when the dojo loader parses the file ?

somefunc: function() {
  var temp = this;
  dojo.xhrPost({
      url: ajaxURL,
      content: adata,
      load: function(data) {
          alert(temp);//will temp refer to what i want it to?
      }
  });
},

Is there a better solution ?


dojo.hitch Would look nicer

Inline anonymous functions are the pain... Try to avoid usage of nesting like declare(.., { foo: new Stuff({ func1: function() { xhr.send({load: function() { }})})});

but in your case, temp Does reference 'this'

the prettier would be

on: function() {
  xhr.send({
   load: lang.hitch(this, then)
  });
},
then: function(data, io) {
  alert(typeof this.on == "function" + "==true");
}


Your example solution is exactly how it's done. Many people use the convention of naming the variable to be bound 'self'.

var self = this;


For reasons explained in the answer to this question and because it's a Douglas Crockford convention, I prefer to use:

var that = this;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜