views:

66

answers:

2

so im trying to write a new jquery plugin.

base (this is not my plugin, just for better understanding):

(function($) {
    $.fn.mySuperCoolPlugin = function(options) {

        // Build main options before element iteration
        var opts = $.extend({}, $.fn.mySuperCoolPlugin.defaults, options);

        var editText= 'pre ' + opts.text + ' post';


        return this.each(function() {
            $(this).html(editText);
        });

    }

    // Default settings
    $.fn.mySuperCoolPlugin.defaults = {
        text: 'hi'
    }

})(jQuery);

now after running my plugin i want to do some additional functions on it.

var plug = $('.text').mySuperCoolPlugin({text: 'running it'});
plug.runAnotherFunction('blabla');
// this for example should set the html to "pre running it post blabla"

plug.runAnotherFunction for example now should extend my previos text and add the text i entered.

do you know what i mean? how to add extra funtions to my plugin? i only see plugins you run once with some options.

leave a comment if something is unclear, thanks!

+1  A: 

Just add the function under your plugin:

   (function($) {
        $.fn.mySuperCoolPlugin = function(options) {

            // Build main options before element iteration
            var opts = $.extend({}, $.fn.mySuperCoolPlugin.defaults, options);

            var editText= 'pre ' + opts.text + ' post';


            return this.each(function() {
                $(this).html(editText);
            });

        }

        // Default settings
        $.fn.mySuperCoolPlugin.defaults = {
            text: 'hi'
        }

        $.fn.mySuperCoolPlugin.runAnotherFunction = function(){
            return "this is another function";
        }

    })(jQuery);
Brian Stoner
this will not work. check my second code block to know what i want.
choise
A: 

Hi,

you need to create wrapper method. And there is one important rule: It must return the wrapped set. So you must return 'this' (refers to the wrapped set) to allow chaining (what you also needs). You can do this using following pattern:

(function($){
  $.fn.runAnotherFunction = function() {
    // put your code here
    // but you have to return 'this' to allow the chaining
  }
})(jQuery);

Or, better to say (in order to iterate over all wrapped sets inside):

(function($){
  $.fn.runAnotherFunction = function() {
    return this.each(function(){
      // put your code here
    });
  }
})(jQuery);
zbynour
thanks but what do do then? now i've got this wrapper function returning itself. and how do i now add this extra functions ?
choise
As you have mySuperCoolPlugin(options) function, you can add the second one (which appends the text to the end of the element content): $.fn.runAnotherFunction = function(text) { return this.each(function() { $(this).append(text); });};Then you can call as you wrote above with 'blabla' parameter. That's what you want if i understand, isn't it?
zbynour