سؤال

I have some conceptual problem with using Dojo's class-like objects created with dojo/_base/declare.

I have created the following module:

define(["dojo/_base/declare", ....], function(declare,....){
    return declare('my.widget', null ,function(..){
     startup: function() {
       ....
       new Button({onClick: this.newItem}, newButtonNode)
     },
     newItem: function() {
       this.openDialog({}, this.saveItemCallback)
     },
     openDialog: function(item,callback){...},
     saveItemCallback: function(item){....}
    })
})

The problem is, that the function newItem isn't functioning, because when it's called from button click, this points to Button widget, and not to the 'my.widget' instance.

I'm confused. How can I refer to the 'my.widget' instance? In the Dojo classes I've read the current instance is available under this.

هل كانت مفيدة؟

المحلول

If you then want to call newItem with the correct scope, you could use the dojo/_base/lang, hitch() function.

define(["dojo/_base/declare", "dojo/_base/lang", ....], function(declare, lang, ....){
    return declare('my.widget', null ,function(..){
     startup: function() {
       new Button({onClick: lang.hitch(this, "newItem"}, newButtonNode)
     },
     newItem: function() {
       this.openDialog({}, this.saveItemCallback)
     },
     openDialog: function(item,callback){...},
     saveItemCallback: function(item){....}
    })
});

The hitch() function will make sure that the this reference is correct. This sounds like real magic, but it uses some kind of reflection behind the screens to execute the function.

What it really does is using the Function.prototype.apply function to get the magic started. As you can read in this article it accepts a context and the parameters. So it will in fact change the this reference when newItem is executed.

نصائح أخرى

You can use dojo.hitch to attach a context to a function:

define(["dojo/_base/declare", ....], function(declare,....){
    var myFunc = dojo.hitch(this, function() { 
       this.openDialog({}, this.saveItemCallback)
    });

    return declare('my.widget', null ,function(..){
     startup: function() {
       ....
       new Button({onClick: this.newItem}, newButtonNode)
     },
     newItem: myFunc,
     openDialog: function(item,callback){...},
     saveItemCallback: function(item){....}
    })
})

By doing so, you are effectively stating that within the anonymous function passed to dojo.hitch, this refers to the first argument passed (which could be any object).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top