Skip to content Skip to sidebar Skip to footer

Could Somebody Explain To Me What Exactly Is Happening In The Dojo's ''dojo/on" Module?

I started fiddling around with Dojo.js and came across a thing I don't understand. I'm trying to create my own widget. The widget would be really simple - it would just query all i

Solution 1:

In your case, this is pointing to the image, and the property counter is undefined. to accomplish this, you can use the dojo/base/lang module

define(
    [                   
        "dojo/_base/declare",
        "dojo/_base/lang", //add this"dojo/query",
        "dijit/_WidgetBase",
        "dijit/_TemplatedMixin",
        "dojo/text!myProject/folder/myWidgetTemplate.html",
    ],
    function(declare, lang, query, _WidgetBase, _TemplatedMixin, template) {
        declare("MyWidget", [_WidgetBase, _TemplatedMixin], {

            templateString: template,
            counter: 0,

            onClick: function(evt) {
                this.counter++;
                console.log(this.counter);
            },

            postCreate: function() {
                //lang.hitch will return a new function with scope changedquery("img").on("click", lang.hitch(this, this.onClick));
            }

        });
    }
);

lang.hitch will return a new function with the scope changed, so when you use this it will be pointing to the want you passed

You can avoid having to use lang by declaring the event in the html, for example

<img src="myImage.jpg" data-dojo-attach-event="onClick: onClick"/>  

Where onClick: onClick can be read as event: functionName, and functionName must exist in your widget.

Note that you can do the same using the native bind function of JavaScript by just doing

query("img").on("click", this.onClick.bind(this));

You can checkout this answer access this on external callback it is not about dojo but Javascript in general.

Post a Comment for "Could Somebody Explain To Me What Exactly Is Happening In The Dojo's ''dojo/on" Module?"