Friday, 26 May 2017

String Value from jQuery becomes undefined when passed as parameter

Good Day,

I am working on a pet project using NodeJS and Electron. It is basically a simple text editor at the moment. However I am running into an issue when trying to pass the value of a text-area to a function prior to saving to file. Specifically when I call a function in another module, the value of the contents becomes 'undefined'. I suspect I am passing it incorrectly, or that it is being over-written between when I make the call and when the call executes, since strings are supposed to be passed by reference.

The code for the Renderer(index.html) is like this :

let otherModule = require('./js/otherModule.js');
let $ = require('jquery');
$('#btn_Save').on('click',() => {
    // get the fileName, if empty propmt user with save dialog, 
    //log it to console for debugging
    var contents = $('#txt_Content').val();
    console.log('with:',contents.substring(0,9),'...');
    var finalContents = contents; // (create a copy?)

    if(//someConditionMet//)
    {
        var otherVar = $('#txt_Other').val();
        console.log('Use:',otherVar.substring(0,9),'...');
        finalContents = otherModule.someFunc(contents, otherVar);
    }
    //do something with final contents.

})// end of On-click

I have used console.log() to extensively evaluate the function and can confirm that up to the call to otherModule, the contents are correct, and match those in the textArea.It is once we are in the 'otherModule' that things go awry.

The code for the otherModule is like this:

const someFunc = function(contents, otherVar)
{
    console.log('DoThings with:',contents.substring(0,9),'...'); 
    // print shows the value to be undefined...
    // do more things
    console.log('Did stuff with otherVar:',otherVar.substring(0,9),'...');
    // prints just fine as as expected.
    // do more things
    return someString;
}

module.exports = {
    someFunc: someFunc
}

As mentioned in the comment, the very first line of the function logs the contents of the console, which displays the substring as 'undefined'.

Thank you for your time and your consideration!

// Extra context//

I have done some searching but beyond learning that strings are passed by reference and are immutable, I have not seen an answer to a question like this. There has been some discussion of closure issues, but usually in the context of events and callbacks, which I do not believe is the context here.



via djscheuf

No comments:

Post a Comment