2

I am trying to write an auto complete jQuery plugin.

The desired usage:

$('.advancedSelect').advancedSelect({/*plugin options*/}).change(function(){})/*.otherJQueryMethods*/;

The implementation:

$.fn.advancedSelect = function({
    return this.each(function(){
         var $advSel = $('<input/>');
         var $el = $(this).after($advSel).hide();
         /* my codes on desired functionalities */
         /* how is it possible to trigger the chained change method */

    });
});
Nick
  • 95
  • 8

1 Answers1

2

In a comment on my soon-to-be-deleted answer (as it answered a question other than your real question, as it turns out), you've said:

I was wondering whether we could have a syntax like this:

$('.advancedSelect').advancedSelect({/*plugin options*/}).onChange(function(){}).css({})

-and by .css I meant any other jQuery's methods.

I would suggest either this:

$('.advancedSelect').advancedSelect({/*other plugin options*/, onChange: function(){}}).css({})

or this:

$('.advancedSelect').advancedSelect({/*plugin options*/}).advancedSelect("onChange", function(){}).css({})

... with a fairly strong preference for the first one. :-)

Re that first option, an adjunct you see a lot is an optional "options" method you can use later to change options::

// Initial setup
$('.advancedSelect').advancedSelect({/*other plugin options*/, onChange: function(){}}).css({})

// Later, I need to change something
$('.advancedSelect').advancedSelect("options", { onChange: function(){}});

Side note: If this change-like method is to register a change handler, why not just use jQuery's change (or on with some plugin-specific event name) and have your plugin raise an event? That's how I would handle any kind of event-related thing in a plugin. Look at bootstrap's use of shown.bs.modal and such, for instance.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Using `on` with custom `adv.change` event and `trigger('adv.change')` could be the best alternative to the case. The code would be like: `$('.advancedSelect').advancedSelect({}).on('adv.change',function(){})` I guess what you'r trying to say is there is no way to achieve the mentioned syntax, right? – Nick Jan 04 '15 at 19:22
  • @hbtb: No reasonable way, no. I mean, you could do this inside your plugin function: `this.onChange = function() { ... };` (e.g., adding a function to *just that one jQuery object*), but I wouldn't call that reasonable. I'd definitely go with your own event name and using `on`. – T.J. Crowder Jan 04 '15 at 19:28