Page 1 of 1

Calling JS functions in Widget

Posted: Wed Mar 01, 2017 8:39 am
by VLNinja70
Hi guys,
I'm trying to build a basic widget where I have a html button that is built dynamically with JS and has an onclick function.
The problem I have is my browser keeps yelling saying that it can't find the function I'm trying to call from my button.
Error on the browser:
=============================================================================
Fatal Error:

Uncaught ReferenceError: clicky is not defined
Reported By:

http://localhost/lansav14/dev/webeditor ... eloper=yes, line 1

=============================================================================

I've tried putting the function in my method, outside the method prototype, and outside all of the prototypes.
I can't seem to find a place for it to be where it can be found?
Are widgets not meant to do stuff like this or am I just going about this wrong?

Thanks!

Code: Select all

function( PROTOTYPE, WIDGET )
{
  PROTOTYPE.onCreateInstance = function()
  {
    this.Caption = 'My Widget';
  }

  PROTOTYPE.onRealizeControl = function( parentDiv )
  {
    this.container = parentDiv;
  }

  PROTOTYPE.onSizeChanged = function()
  {

  }
  
  PROTOTYPE.setup = function()
  {
    var mainCmd = document.createElement("BUTTON");
    var cmdTxt = document.createTextNode("I AM A BUTTON");
    mainCmd.setAttribute('id', "mainButton");
    mainCmd.setAttribute('onClick', "clicky()" );
    mainCmd.appendChild(cmdTxt);
    this.container.appendChild(mainCmd);
  }

  return WIDGET.Completed;
}

function clicky() {
  alert("it worked!");
}

Re: Calling JS functions in Widget

Posted: Wed Mar 01, 2017 9:01 am
by jyoung
Instead of setting the onclick attribute, you can define the function directly or use an event listener.

Code: Select all

  //
  // Setup - Set it Up
  //
  PROTOTYPE.Setup = function()
  {
    var mainCmd = document.createElement("BUTTON");
    var cmdTxt = document.createTextNode("I AM A BUTTON");
    mainCmd.setAttribute('id', "mainButton");

    // one way
    //mainCmd.onclick = function() {
    //  alert('Hello from onclick')
    //};

    // another way
    mainCmd.addEventListener("click", function() {
      alert('Hello from event listener');
    }, false);

    mainCmd.appendChild(cmdTxt);
    this.container.appendChild(mainCmd);
  }

Re: Calling JS functions in Widget

Posted: Wed Mar 01, 2017 9:14 am
by VLNinja70
Ah ok, so just do it all inline.
That did the trick!
Thanks Joe!

Re: Calling JS functions in Widget

Posted: Wed Mar 01, 2017 9:19 am
by jyoung
If you don't want to do it inline, you can do it like this

Code: Select all

    mainCmd.onclick = clicky;
Notice no parentheses () at clicky. Putting the parentheses would call the function when it executes, here we essentially setting a function pointer.