jqueryjquery-pluginsjquery-widgets

Trigger an event when a configuration option in a jQuery plugin is changed? Option or public method?


I'm working on the next version of my jQuery plugin for smooth scrolling (Smooth Div Scroll). This is a stateful plugin based on the jQuery widget factory so the state of the plugin can be altered after the plugin has been initialized. Either the user can alter the configuration options of the plugin or use one of the public methods I supply.

In this plugin, I have an option that is a boolean: hotSpotScrolling (true/false). If the user sets this option to true as a part of the options supplied when the plugin is initialized, hot spots for scrolling are activated. And vice versa - inactivated if it's set to false.

If the user alters this option after the plugin has initialized, I need the plugin to respond to this alteration. So if the user sets hotSpotScrolling to false I need to hide the hot spots and inactivate some other stuff related to hot spot scrolling. Vice versa, if the user sets hotSpotScrolling to true I need to show the hot spots and activate some other stuff.

But as far as I know, there is no way of making a jQuery plugin respond to changes in the options along the lines of the scenario I just described and I'm not even sure that it's desirable. To me, it sounds more like a task for public methods? So instead of altering the option, the user would call a public method and inside this method, I write code that alters the state of the plugin.

I'm interested in best practice when it comes to choosing between altering options and calling public methods in jQuery plugins and preferably some nice examples with code that sheds a light on this dilemma.


Solution

  • Check out how the updated tabs widget handles options getting changed after initialization:

    https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.tabs.js#L113-140

    The updated accordion does the same thing:

    https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.accordion.js#L157-191

    That is what you will want to do.