Skip to content

Commit 4cf8c56

Browse files
committed
Adding article on jQuery widget method invocation.
1 parent 1458b4a commit 4cf8c56

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
---
2+
title: Widget Method Invocation
3+
level: intermediate
4+
---
5+
6+
Widgets created with [the widget factory](/jquery-ui/widget-factory/) use methods to change their state and perform actions after initialization. There are two ways widget methods can be invoked - through the plugin created by the widget factory, or by invoking the method on the element's instance object.
7+
8+
### Plugin Invocation
9+
10+
To invoke a method using the widget's plugin, pass the name of the method as a string. For example, here is how you call the [dialog widget's `close()` method](http://api.jqueryui.com/dialog/#method-close).
11+
12+
```
13+
$( ".selector" ).dialog( "close" );
14+
```
15+
16+
If the method requires arguments, pass them as additional parameters to the plugin. Here is how you call [dialog's `option()` method](http://api.jqueryui.com/dialog/#method-option).
17+
18+
```
19+
$( ".selector" ).dialog( "option", "height" );
20+
```
21+
22+
This returns the value of the [dialog's `height` option](http://api.jqueryui.com/dialog/#option-height).
23+
24+
### Instance Invocation
25+
26+
Under the hoods, every instance of every widget is stored on the element using [`jQuery.data()`](http://api.jquery.com/jQuery.data/). To retrieve the instance object, call `jQuery.data()` using the widget's full name as the key. Let's look at each.
27+
28+
```
29+
var dialog = $( ".selector" ).data( "ui-dialog" );
30+
```
31+
32+
After you have a reference to the instance object, methods can be invoked on it directly.
33+
34+
```
35+
var dialog = $( ".selector" ).data( "ui-dialog" );
36+
dialog.close();
37+
```
38+
39+
In jQuery UI 1.11, the new `instance()` method will make this process even easier.
40+
41+
```
42+
$( ".selector" ).dialog( "instance" ).close();
43+
```
44+
45+
### Return Types
46+
47+
Most methods invoked through the widget's plugin will return a `jQuery` object so the method call can be chained with additional jQuery methods.
48+
49+
```
50+
$( ".selector" )
51+
.dialog( "close" )
52+
.css( "color", "red" );
53+
```
54+
55+
The exception to this are methods that return information about the widget. For example [dialog's `isOpen()` method](http://api.jqueryui.com/dialog/#method-isOpen).
56+
57+
```
58+
$( ".selector" )
59+
.dialog( "isOpen" )
60+
// This will throw a TypeError
61+
.css( "color", "red" );
62+
```
63+
64+
This produces a `TypeError` error as `isOpen()` returns a boolean, not a jQuery object.

0 commit comments

Comments
 (0)