Skip to content

Instantly share code, notes, and snippets.

@ehynds
Created October 13, 2010 12:30
Show Gist options
  • Save ehynds/623931 to your computer and use it in GitHub Desktop.
Save ehynds/623931 to your computer and use it in GitHub Desktop.
// connect the widget obj to jQuery's API under the "foo" namespace
$.widget.bridge("foo", Widget);
// now you can do...
var instance = $("#elem").foo({
baz: true
});
/*
which just did three things:
1. checks to see if the object has already been inited.
if it has, automatically calls the option and _init
methods.
2. creates a new instance of Widget, passing in the options
hash and the element the widget was initialized upon.
3. stores the instance in the element's $.data cache.
*/
// your widget instance exists in the elem's data
instance.data("foo").element; // => #elem element
// bridge allows you to call public methods...
instance.foo("publicFn"); // => "public method"
// bridge prevents calls to internal methods
instance.foo("_privateFn"); // => #elem element
// bridge prevents method calls to uninitialized widgets.
// (we only initialized foo on #elem above)
// thrown error introduced in v1.8.5
$("#bar").foo("publicFn"); // => "cannot call methods on 'foo' prior to initialization..."
// bridge prevents calls to non-existing methods
// thrown error introduced in v1.8.5
instance.foo("hai"); // => "no such method 'hai' for foo instance"
// bridge let's you change an option after initilization
instance.foo("option", "baz", false);
// or just get an existing option's value
instance.foo("option", "baz"); // => false
// if you attempt to re-initialize the widget...
instance.foo({ baz:false });
/*
bridge will take the EXISTING instance, run the "options"
method to update any new options that were passed in,
and automatically fire the _init() method.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment