Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - Widget Public Methods

If I create a JQuery widget (code example below), and then define a "public" method, is there any other way to call the method other than using the following form?

$("#list").list("publicMethod");  

I would like to create a series of widgets that all define the same methods (basically implementing the same interface), and be able to call the method without knowing anything about which widget I currently am invoking the method on. In the current form, I need to know that I am executing the method on the "list" widget.


Below is an example of creating a widget with the "public" method.

 (function($) {     var items = [];     var itemFocusIdx = 0;      $.widget("ui.list", {         // Standard stuff         options : { ... },         _create : function() { ... },         destroy : function() { ... },          // My Public Methods         publicMethod : function() { ... }         ...     }); }(jQuery)); 
like image 794
Steve Avatar asked May 05 '10 17:05

Steve


2 Answers

jQuery UI widgets use jQuery's $.data(...) method to indirectly associate the widget class with the DOM element. The preferred way to call a method on the widget is exactly what was described by Max...

$('#list').list('publicMethod'); 

...but if you want to field a return value, you'll have better luck calling it this way, via the data method:

$('#list').data('list').publicMethod(); 

However, using the second way side-steps the whole jQuery UI widget pattern, and should probably be avoided if possible.

like image 78
cdata Avatar answered Oct 09 '22 08:10

cdata


Slightly off-topic, I know, but you may want to look at jquery Entwine.

This provides a form of inheritance and polymorphism which allows some clever behaviour with simple code. It sounds like this would do what you are trying to do.

like image 36
Luke H Avatar answered Oct 09 '22 09:10

Luke H