Reputation: 3243
I am having trouble finding out how to manipulate a custom function I have written after binding it to an element. E.g. I have a function
jQuery.fn.myPlugin = function(opts) {
this.someFunction = function() { };
$(this).keypress(function() {
// do something
someFunction();
});
};
$('#some-element').myPlugin({ someOption: 'option'});
What I would like to do is set the optional function (someFunction) after the plugin has been set. So something along the lines of
$('#some-element').myPlugin("someFunction", function() {
// do something
});
I know I will need more parameters in myPlugin, and check whether it is the initial call (with opts) or something is being changed after initialization. But not quite sure how to go about doing this.
Upvotes: 0
Views: 1114
Reputation: 171669
Read the Plugins/Authoring page of jQuery docs.
Can use this plugin development pattern (see Plugin Methods section):
(function( $ ){
var methods = {
init : function( options ) {
// THIS
},
show : function( ) {
// IS
},
hide : function( ) {
// GOOD
},
update : function( content ) {
// !!!
}
};
$.fn.tooltip = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.tooltip' );
}
};
})( jQuery );
Upvotes: 1
Reputation: 19093
Have you considered using the jqueryui widget factory ? This has support for changing options after creation, as well as custom methods and events.
http://wiki.jqueryui.com/w/page/12138135/Widget%20factory
Upvotes: 1