0

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

3
  • Have you checked the 'one' method in jquery?
    – Poul Bak
    Commented Apr 10, 2016 at 11:01
  • 1
    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 instead
    – A. Wolff
    Commented Apr 10, 2016 at 11:25
  • @PoulBak I need the event to run EVERY time a change occurs, in addition to once before anything happened. @A.Wolff Sure! Editing
    – oriadam
    Commented Apr 11, 2016 at 12:32

2 Answers 2

1

Updated answer:

You can create a custom event to fit your needs:

(function() {
  var originalJqOn = jQuery.fn.on;
  jQuery.fn.extend({
    onAndFirst: function(evtName, fn) {
      fn();
      this.on(evtName, fn);
    }
  });
})();

var base = "/act/";
var update_go = function() {
  // in first run "this" equals the global window object
  if (this === window) {
    $('#go').prop('href', base + $("#sel").val());
    console.log("href set to: " + $("#sel").val());
  } else {
    $('#go').prop('href', base + $(this).val());
    console.log("href changed to: " + base + $(this).val());
  }
};

$('#sel').onAndFirst('change', update_go);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="sel"><option>A<option>B<option>C</select>
<a id="go" href="#">Go</a>

Here is a JsFiddle: https://jsfiddle.net/2zg8dgf4/2/

JsBin (to see logs): http://jsbin.com/wetocayala/1/edit?html,js,console,output

Resource: https://learn.jquery.com/plugins/basic-plugin-creation/

There is an issue here with the window object (please refer to the comment in my solution) that you should consider it's handling (it really depends on how you're gonna use this in the real case you are dealing with, up to you).


Original answer:

I would go with the function call, with a little change:

// function
var first_and_change_call=function(){
   update_selected(this);
}.call($('#sel_call')[0]);

Update Fiddle: https://jsfiddle.net/Lu9ym1xy/14/

If you need something more complex then that, please provide more details.

4
  • Nice idea. I can also use this method with an inline anonymous function, directly inside the .on, but I guess that wouldn't be readable. I was hoping to expand jQuery events, adding an event that simply run once, in any case, when .on is called.
    – oriadam
    Commented Apr 11, 2016 at 12:26
  • 1
    I've updated my answer to have a custom event that should fit your needs.
    – Or A.
    Commented Apr 13, 2016 at 13:22
  • Or - Exactly what I needed, Thank you! Just some important fixes - fn functions this is a jQuery element (need to use .each when calling the handler) + they must return this to allow chaining. Here's an update jsfiddle.net/2zg8dgf4/3
    – oriadam
    Commented Apr 17, 2016 at 8:56
  • jQuery.fn.extend({ onAndFirst: function(evtName,fn) { return this.on(evtName, fn).each(fn); } });
    – oriadam
    Commented Apr 17, 2016 at 18:17
0

// call the handler immediately in addition to being triggered by event
jQuery.fn.onAndNow = function(events, func) {
    // TODO: Support the data object
    return this.each(func).on(events, func);
  };
///////////////////////////////////

// usage example:
$('#select').onAndNow('change', function() {
  var val = $(this).val();
  $('#go').prop('href', '//example.com/?' + val).html('Go to ' + val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select">
    <option>save a life</option>
    <option>eat spaghetti</option>
</select>
<a id="go" target="_blank">Go nowhere?</a>

https://jsfiddle.net/oriadam/v91wepuk/

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.