简体   繁体   中英

Immediately trigger function if Global var becomes undefined

I have global variable eg window.remote.storageData that is filled on script running. However, in some cases it becomes undefined explicitly. In those cases I`d like to trigger function in order to reload it. I used setInterval for this:

setInterval(function(){...},timer);

However, if the var becomes undefined in range of timer I got errors in my code. Tiny timer gap is stuck my application, those the solution with timer less then 500 is not working well.

Is there are some ways to trigger function immediately when variable value is changed?

If you use ES5 browsers and remote is not frozen you can define a property with custom get/set.

(function(remote) {
  var value = remote.storageData;

  try {
    Object.defineProperty(remote, 'storageData', {
       get: function() { return value;}

       set: function(newVal) {
         if(typeof newVal === 'undefined') {
            newVal = //some code to get value
         }

         value = newVal
       }
    })
  } catch(e) {
     console.log(e)
  }
}(window.remote))

But some code could still replace entire window.remote object. In this case you'll need to define remote property with custom get/set on window itself.

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