0

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.

2 Answers 2

1

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 ); 
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.