简体   繁体   中英

How to use or create a non-global javascript variable cache from a html accessible tag

I have a javascript function that needs to be invoked 'onkeyup' from an input field:

<input id="searchSurname" type="text" name="surname" onkeyup="queryPatients()" />

Yet, for the life of the session (or so long as the user is using that page) the function needs to be able to cache some results from each time the event has happened.

In order to prevent my cache variables being globally accessible (nasty nasty) I enclose them in an anonymous function (a pattern I've seen quite a bit)

(function(){

    var cacheSurname = "";
    var cacheGivenNames = "";

    function queryPatients() {

        var surname = $('#searchSurname').val();
        var givenNames = $('#searchGivenNames').val();

        // do some more work, cache the variables 
        cacheSurname = surname;
        cacheGivenNames = givenNames;
    }   
}).call(this);

Yet, being so enclosed, my input field is unable to invoke the method.

Is there an appropriate solution? Or do I have to resort to a global variable after all?

Since you are using jQuery, you can bind to the key up event inside of that "private" scope.

(function(){

    var cacheSurname = "";
    var cacheGivenNames = "";

    function queryPatients() {

        var surname = $('#searchSurname').val();
        var givenNames = $('#searchGivenNames').val();

        // do some more work, cache the variables 
        cacheSurname = surname;
        cacheGivenNames = givenNames;
    } 
    $('#searchSurname').on('keyup', queryPatients);
}).call(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM