简体   繁体   中英

how to execute? jquery.on event with OR when some condition is true?

some Javascript code is to run only after certain events for example (jquery mobile):

$(document).on('pageinit', function(){ run code which needs an inited page. });

What javascript/jquery patern can execute the function when a condition is true or wait for the event when the condition is not true yet.

(Some scripts are dynamically loaded and do not execute as the event has then long ago been fired)

Currently i use:

if( myVar == 'pageInit'){ run the code which needs an inited page }
else{
  $(document).on('pageinit', function(){ run the code which needs an inited page }
}

Is there a pattern for handling this better?

You can try

$(document).on('pageinit', function () { /* do stuff here */ }).trigger('pageinit');

That both sets it up for later triggers and also runs it the very first time after setup.

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