I need to run an event handler once, when on
is called, in addition to on change
. I have a <select>
that changes the behavior the page when changed. It also set a default value for that button, which is why the change
handler should run on the first time even before an actual change
has occurred.
Example (the actual code is much more complicated):
<select id="sel"><option>A<option>B<option>C</select>
<a id="go" href="#">Go</a>
<script>
var base = "/act/";
function update_go(){
$('#go').prop('href',base+$(this).val());
}
$('#sel')
.on('change',update_go) // update button when select is changed
.each(update_go); // update button with the default value of the select
// todo: check: when select value is remembered by browser, does it work as it should?
</script>
I would like to extend jQuery events, allow an event that will always run, once, when .on
is called. This way I could omit the .each
and use inline anonymous functions. Something like that:
$('#sel').on('change runonce',function(){
$('#go').prop('href',base+$(this).val());
});
I don't want to call .trigger('change')
because it may run event handlers that I'm not aware of. Also, calling trigger
is amazingly costly, when many elements are involved; which is why I don't want to call trigger('runonce')
.
Using each
or a function call works much faster, and looks good, but it requires a named function for every event.
Thank you
JSFiddle: https://jsfiddle.net/oriadam/Lu9ym1xy/13/
JSPerf: http://jsperf.com/jquery-custom-trigger-vs-each-vs-function-call1
I have a <select> that changes the behavior of a button when changed. It also set a default value for that button
You should tell us more about this insteadchange
occurs, in addition to once before anything happened. @A.Wolff Sure! Editing