Vince Vince - 7 months ago 12
Javascript Question

How do I use a function as a variable in JavaScript?

I want to be able to put the code in one place and call it from several different events.

Currently I have a selector and an event:

$("input[type='checkbox']").on('click', function () {
// code works here //
});


I use the same code elsewhere in the file, however using a different selector.

$(".product_table").on('change', '.edit_quantity', function () {
// code works here //
});


I have tried following the advice given elsewhere on StackOverflow, to simply give my function a name and then call the named function but that is not working for me. The code simply does not run.

$(".product_table").on('change', '.edit_quantity', function () {
calculateTotals() {
// code does not work //
}
});


So, I tried putting the code into it's own function separate from the event and call it inside the event, and that is not working for me as well.

calculateTotals() {
// code does not work //
}


So what am I doing wrong ?

Answer

You could pass your function as a variable.

You want to add listeners for events after the DOM has loaded, JQuery helps with $(document).ready(fn); (ref).

To fix your code:

 $(document).ready(function() {
   $("input[type='checkbox']").on('click', calculateTotalsEvent)
   $(".product_table").on('change', '.edit_quantity', calculateTotalsEvent)
 });

 function calculateTotalsEvent(evt) {
   //do something 
   alert('fired');
 }

Update:
Vince asked:

This worked for me - thank you, however one question: you say, "pass your function as a variable" ... I don't see where you are doing this. Can you explain ? tks. – Vince


Response:
In JavaScript you can assign functions to variables. You probably do this all the time when doing:

function hello() {
  //
}

You define window.hello.
You are adding to Global Namespace.
JavaScript window object
This generally leads to ambiguous JavaScript architecture/spaghetti code.
I organise with a Namespace Structure.
A small example of this would be:

app.js

var app = {
  controllers: {}
};

You are defining window.app (just a json object) with a key of controllers with a value of an object.

something-ctlr.js

app.controllers.somethingCtlr.eventName = function(evt) {
  //evt.preventDefault?
  //check origin of evt? switch? throw if no evt? test using instanceof?
  alert('hi');
}

You are defining a new key on the previously defined app.controllers.somethingCtlrcalled eventName.

The javascript files would be structured like so:

  +-html
  +-stylesheets
  +-javascript-+
               +-app-+
                     +-app.js
                     +-controllers-+
                                   +-something-ctlr.js

Invoke via chrome developer tools with:

app.controllers.somethingCtlr.myNameIs('Rhys');

You can pass it as a variable like so:

$(document).ready(function() {
  $('button').click(app.controllers.somethingCtlr.eventName);
});

JQuery (ref).

I hope this helps, Rhys