Unable to set an onclick function within a customized dojo widget

I have a custom widget that I've defined as shown below:

dojo.declare('myWidget', [dijit._WidgetBase, dijit._Templated],
{
    'templateString':'<span>' +
            '<a  dojoAttachPoint="linkNode" href="blah.php">' +
                '<img class="thumbNail" src="blahthumb.php" />' +
            '</a>' +
            '<h4 dojoAttachPoint="title" class="title">${blahtitle}</h4>' +
        '</span>',
    'stuff':null,
    'startup':function()
    {
        dojo.connect(this.linkNode, 'onclick', function(e){dojo.stopEvent(e);alert('hi');});
    }
});

When I programmatically create the widget and add it to the page like this:

...
    f = new myWidget(stuff);
    f.startup();    
    li = dojo.create('li', {'class':'thingy'});
    dojo.place(f.domNode, li);
    dojo.place(li, this.gallery); // inside another widget
...

The onclick event connected in the startup method doesn't seem to be firing. I've tried different ways of assigning it but nothing seems to work.

Is there something wrong with the way I'm setting up the onclick event?

Answer №1

It's uncertain why your current approach isn't functioning as expected. One possible reason could be the lack of propagating the method call to startup by incorporating this.inherited(arguments); at the end of the method.

Considering your scenario, an alternative method might be more appropriate. Apart from utilizing dojoAttachPoint, there is also dojoAttachEvent in Dojo. It may be beneficial to implement it like this:

dojo.declare('myWidget', [dijit._WidgetBase, dijit._Templated],
{
    'templateString':
        '<span>' +
            '<a dojoAttachEvent="onClick:_linkNodeClick" href="blah.php">' +
                '<img class="thumbNail" src="blahthumb.php" />' +
            '</a>' +
            '<h4 dojoAttachPoint="title" class="title">${blahtitle}</h4>' +
        '</span>',

    'stuff':null,

    '_linkNodeClick':function(e){
        dojo.stopEvent(e);
        alert('hi');
    }
});

Edit

Upon testing it myself, I was able to make it work with the following adjustments:

dojo.provide("MyWidget");
dojo.declare('MyWidget', [dijit._Widget, dijit._Templated],
{
    'templateString':
        '<span>' +
            '<a dojoAttachPoint="linkNode">' +
                '<img class="thumbNail" src="blahthumb.php" />' +
            '</a>' +
            '<h4 dojoAttachPoint="title" class="title">${blahtitle}</h4>' +
        '</span>',

    'startup':function()
    {
        dojo.connect(this.linkNode, 'onclick', function(e){dojo.stopEvent(e);alert('hi');});
    }
});

To initiate it, I needed to attach it to the DOM before invoking the startup function.

var f = new MyWidget();
dojo.body().appendChild(f.domNode);
f.startup();

The only modifications made were adding dojo.provide(...) and using _Widget instead of _WidgetBase. Additionally, reordering the steps as suggested. Now, clicking on the image triggers the alert "hi" without navigating to the link.

Answer №2

After careful investigation, I was able to uncover the issue. Surprisingly, it had nothing to do with the widget's construction process but rather a particular function that altered the widget right after execution. The peculiar part is how this alteration led to the disappearance of onclick events. Analyzing further, I found that it was due to the manipulation of the innerHTML attribute within certain dom nodes of the widgets. Once I disabled that specific segment of code, everything started functioning smoothly again.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Styling a table based on specific conditions using Angular and JavaScript

I am trying to conditionally style the text in the table based on the time elapsed since the last ping. Specifically, I want to change the color of the text from green to red once 5 minutes have passed and vice versa. <form name="myform" data-ng-submit ...

I am experiencing some difficulty with the GetServerDate using the JSON protocol in JQuery; it's

I am facing an issue while trying to execute a basic ajax call to fetch data from a file on a server. Even though I can access the file via the web browser and have diligently followed tutorials related to this topic, I have hit a dead end. Here is the sn ...

Listening for a click event on a newly added element using JQuery

I am relatively new to using JQuery and I have encountered an issue with adding a click event listener for a dynamically created button. When the user clicks on the first button, my function successfully adds a second button to a div. However, I am facing ...

The Less compiler (lessc) encounters an issue on a fresh operating system. ([TypeError: undefined is not a function])

After setting up my new development environment on Windows 10, I encountered an issue with less. Following the instructions on lesscss.org, I installed less using: npm install -g less The installation process completed without any errors. However, when ...

Cross-Origin Resource Sharing (CORS) verification for WebSocket connections

I am currently utilizing expressjs and have implemented cors validation to allow all origins. const options = { origin: ['*'], credentials: true, exposedHeaders: false, preflightContinue: false, optionsSuccessStatus: 204, methods: [&a ...

The issue of for loops malfunctioning in JavaScript when using a variable declared in Node.js and passed to Jade

Currently, I am delving into the world of node.js and JADE but seem to be encountering a challenge when it comes to implementing a for loop within a JavaScript block in a jade file. My approach involves experimenting with a basic code where I pass an array ...

Unable to find the module... designated for one of my packages

Within my codebase, I am utilizing a specific NPM package called my-dependency-package, which contains the module lib/utils/list-utils. Moreover, I have another package named my-package that relies on my-dependency-package. When attempting to build the pr ...

Incorporating script within an ASPX webpage

I've been struggling with using this code on an ASPX page. I keep trying to implement it within a text box on the same page, but without success. Strangely though, I can successfully use the script within a text box in my master page. Any assistance w ...

Is there a way to store the URLs that a user visits locally with a Chrome extension using JavaScript?

I am working on a Chrome extension that will save the URL link of the active tab when a user clicks on the extension icon. The goal is to store this URL in local storage and keep it saved until the active window is closed. I have set up an array called tab ...

I just installed Electron on my Mac using the command 'sudo npm install electron -g', but now I am encountering an error. How can I resolve this issue

When I first attempted to run the command, I encountered 'Permission Denied' errors so I added sudo before the command as suggested. Another recommendation was to install the electron folder at /usr/local/lib/node_modules, but even after reinstal ...

Utilizing ReactJS to fetch data from Material-UI's <TableRow/> component upon selection - a comprehensive guide

I've integrated Material-UI's <Table/> (http://www.material-ui.com/#/components/table) component with <TableRow/> containing checkboxes in a ReactJS project. While I can successfully select rows by checking the boxes, I am struggling ...

Tips for adding a dynamic variable into a react JSX map function

I have a component that receives a props with the value of either 'A', 'B', or 'C' based on the selection made in the parent element. The challenge is to use this props to dynamically select an option list locally, instead of ...

the router is having trouble choosing the right function

When attempting to log in a user using postman with the URL http://localhost:3000/login, it seems to always trigger the register function instead. The code itself is working fine, but it's just routing to the wrong function. How can I redirect it to t ...

Display information when hovering over a tag

I'm working on adding a feature where hovering over a link will display a tooltip. For reference, here is an example: https://i.stack.imgur.com/K84Wf.png Are there any alternative JavaScript libraries that offer this functionality? (ideally similar ...

What methods can I use to compare a React Component across multiple pages with Cypress?

One task I am trying to tackle is comparing a component on one page with the same component on another page using Cypress. For example, let's say I have a Pricing Component on the Home page, and I want to verify if the values on the Pricing Page are i ...

Refresh a webpage using JavaScript (inside a jquery ajax call)

Seeking guidance on how to reload a page using JavaScript, I have created the following function: function update(id, name) { if(/^\d+$/.test(id)) { $.ajax({ url: baseurl + "/url/action/param/" + id + "/param2/" + unescap ...

Understanding the distinction between assigning a value and setting text through JSE in Selenium using C#

Utilizing the IJavaScriptExecutor to set the attribute value can sometimes result in the text box containing the set value, but not displaying it as text. In some cases, the input is sent normally to certain text boxes, while for others, it is only setting ...

The npm package for google-spreadsheet.js is experiencing issues and is not functioning correctly when trying to replicate the GitHub

After attempting to implement the basic example code provided at https://github.com/theoephraim/node-google-spreadsheet, I encountered an issue. For instance: const { GoogleSpreadsheet } = require('google-spreadsheet') const creds = require(&apo ...

Utilizing Unidirectional Binding within an AngularJS Directive

I have a directive set up here: myApp.directive('stoplight', function() { return { restrict:'E', transclude: true, scope: { value: '@' }, link: function(scope, element) ...

React-Bootstrap Popup encounters overlay failure

While using the Tooltip without an OverlayTrigger, I encountered the following error: webpack-internal:///133:33 Warning: Failed prop type: The prop overlay is marked as required in Tooltip, but its value is undefined. The code snippet causing the issu ...