Fred J.
Fred J.

Reputation: 6029

calling a client side function

This Meteor code needs to call function cleanSerializedArray(); in header.js which is defined in main.js, both files are under the client directory.

Browser console error:

Uncaught ReferenceError: cleanSerializedArray is not defined

But when the definition is moved to the same file "header.js", the console says

undefined

Why are those 2 un expected results, I expected to see the function work in both cases? Thanks

'use strict';
Template.header.events({
  'click .mainMenu': function () {
    //control the footer visibility
    if (Session.get('showMainMenu')) {
      Session.set('showMainMenu', false);
    } else {
      console.log(cleanSerializedArray()); //<------- called
      //Meteor.call('storeUserInputs', objArray);
      Session.set('showMainMenu', true);
    }
});

function cleanSerializedArray() {
   return $('form').serializeArray().forEach(function (item) {
    item.value = item.value.replace(/[^0-9a-zA-Z]/g, '');
  });
}

Upvotes: 0

Views: 45

Answers (1)

Siguza
Siguza

Reputation: 23850

You get undefined because Array.prototype.forEach always returns undefined.
You probably want to change your cleanSerializedArray function to this:

function cleanSerializedArray() {
    var array = $('form').serializeArray();
    array.forEach(function (item) {
        item.value = item.value.replace(/[^0-9a-zA-Z]/g, '');
    });
    return array;
}

As for your ReferenceError, that is usually caused by one of two things:

Scoping:

window.addEventListener('DOMContentLoaded', function()
{
    function myFunc(){ /* ... */ }

    /* some code that uses myFunc */
});
/* myFunc is not available out here */

Timing:

window.addEventListener('DOMContentLoaded', function()
{
    window.myFunc = function(){ /* ... */ }

    /* some code that uses myFunc */
});
/* myFunc is not available yet */

Since you seem to be calling the function only from an event handler, a scoping issue is far more likely than a timing one.
Try declaring the function instead as:

window.cleanSerializedArray = function() {
    // ...
};

Upvotes: 1

Related Questions