Skip to content

Instantly share code, notes, and snippets.

Created July 8, 2011 14:29
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save scottjehl/1071960 to your computer and use it in GitHub Desktop.
Save scottjehl/1071960 to your computer and use it in GitHub Desktop.
Self-init a jQuery Mobile plugin
// First, let's define a widget/plugin called "foo"
// Either using jQuery's $.fn plugin namespace, for simple stateless plugins...
$ = function(){
// In this scope, this refers to the element on which the plugin foo() was called
// manipulate it and return this at the end, so it can be chainable
// note: read more about simple jQuery plugin development here:
// ...or using the widget factory, for more robust, stateful plugins
$.widget( "", $.mobile.widget, {
options: {
bar: true,
baz: false
_create: function() {
// _create will automatically run the first time this widget is called
// Put the initial widget setup code here, then
// You can access the element on which the widget was called via this.element
// The options defined above can be accessed via this.options
// Private methods/props start with underscores
_dosomething: function(){ ... },
// Public methods like these below can can be called externally: $("#myelem").foo( "enable", arguments );
enable: function() { ... },
disable: function() { ... },
refresh: function() { ... }
// note: more about the widget factory here:
// Regardless of the way you set up the plugin, either widget above can be called like this:
$("#myelem").foo( options );
// Let's self-init this widget whenever a new page in jQuery Mobile is created.
// jQuery Mobile's "page" plugin dispatches a "create" event
// when a jQuery Mobile page (found via data-role=page attr) is first initialized.
// We can listen for that event (called "pagecreate" ) and run our plugin automatically whenever a new page is created.
$( document ).bind( "pagecreate", function( e ){
// In here, refers to the page that was created (it's the target of the pagecreate event)
// So, we can simply find elements in this page that match a selector of our choosing, and call our plugin on them.
// Here's how we'd call our "foo" plugin on any element with a data-role attribute of "foo":
$( ).find( "[data-role='foo']" ).foo( options );
// Or, better yet, let's write the selector accounting for the configurable data-attribute namespace
$( ).find( ":jqmData(role='foo')" ).foo( options );
// That's it. Now you can simply reference the script containing your widget and
// pagecreate binding in a page running jQuery Mobile site and it will automatically run like any other jQM plugin
// One last thing... Don't forget to wrap all this $-using code in a closure that ensures $ refers to jQuery object. like this:
(function( $ ){
// You can use $ safely in here!
}( jQuery ));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment