Dynamically add imported function call to onclick

325 views Asked by At

I have a script that loads information and uses it to add an onclick call to links. I think it will be clearer with an example:

Script.js

const app = {

   init: function() {
     ...
     var link = document.createElement("a");
     link.setAttribute("onclick", "goToTicket(" + data.tickets[i].id +');');
     link.setAttribute("href", "javascript:void(0);");
     link.innerHTML = "Ticket " + data.tickets[i].id;
     cell1.appendChild(link);
   },

    ...

    goToTicket: function(ticketId){
       //Some code
    },
}

Sidebar.js

import app from './script.js';
...

iframe.html

...
<script type="module" src="lib/javascripts/ticket_sidebar.js"></script>
...

When I click on the link generated in the code, I get an error

TypeError: app.goToTicket is not a function at HTMLAnchorElement.onclick

I've tried different things like adding the goToTicket directly in Sidebar.js but I can get it to run.

Any ideas on what I'm missing?

Thanks,

2

There are 2 answers

0
Ignacio On BEST ANSWER

Eventually ended up using jQuery. Here is how script.js looks now:

Script.js

const app = {

   init: function() {
     ...
     var link = document.createElement("a");
     link.setAttribute("href", "javascript:void(0);");
     link.innerHTML = "Ticket " + data.tickets[i].id;
     link.className = "ticket " +  data.tickets[i].id;
     $(document).on("click",".ticket."+data.tickets[i].id, data.tickets[i].id,app.goToTicket);
     cell1.appendChild(link);
   },

    ...

    goToTicket: function(ticketId){
       //Some code using ticketId.data
    },
}

The function is called correctly when I click the links

1
Nam On

you can try add module.exports = app; bottom file Script.js