开发者

Jquery: i have a function $.fn.my_function with other functions inside, how can i call them?

Suppose i have this ($ = jquery):

 $.fn.my_function = function() {
    function foo() 
    { 
       //do something 
    };

    function bar() 
    { 
       //do something other
    };

 }

I lauch 开发者_开发问答this with $('.my_class').my_function();

Now, i need to call foo and bar on callback to certain events.

How can i call them?


You'll have to expose them to the "outside world" somehow. Currently, they are only visible within my_function so you won't be able to call them from anywhere else.

The most naive way to fix this would be something like:

var foo;
var bar;
$.fn.my_function = function() {
    foo = function() {
       //stuff
    };
    bar = function() {
       //stuff
    };
};

The same concept could be applied to place references to them anywhere that makes sense for your usage.


It seems that you're trying to build a jQuery plugin. You should constrain your plugin's methods to a private scope, and you should also iterate over the elements given to the plugin by the jQuery selector, and return them by using jQuery's "each" to preserve the chaining abilities:

// wrap the plugin code inside an anonymous function 
// to keep the global namespace clean   
(function($){
    $.fn.my_function = function() {
        return this.each(function(){
            function foo() {
                // stuff here
            }
            function bar() {
                // stuff here
            }
            // now you can use your foo and bar which ever way you want
            // inside the plugin
            $(this).focus(function(event){
                // do some stuff
                ...
                // call the function defined previously in the plugin code
                foo(); 
            });
            $(this).blur(function(event){
                // do some stuff
                ...
                // call the function defined previously in the plugin code
                bar();
            });
        });
    };
})(jQuery);

You might wanna have a look at these articles for more info on jQuery plugin development: http://www.learningjquery.com/2007/10/a-plugin-development-pattern

http://docs.jquery.com/Plugins/Authoring

However, if you're doing just some "utility"-type functions, you can just tie them to jQuery namespace like this:

$.foo = function(){
         // do stuff
    };
$.bar = function(){
        // do stuff
    };


HTML

<p id="hello">aaa</p>
<p id="hola">sss</p>
<div id='result'></div>

JS

$.fn.my_function = function() 
{
    this.foo = function(xref) {
       $("#result").append("<div>"+xref+".foo " + $(this).html() +"</div>");
    };

    this.bar = function(xref) {
       $("#result").append("<div>"+xref+".bar " + $(this).html() +"</div>");
    };

    return this;
};

var ee1 = $("#hello").my_function();
var ee2 = $("#hola").my_function();

ee1.bar("ee1");
ee2.bar("ee2");
$("#hello").html("hello hellboy");
ee1.foo("ee1");
ee2.foo("ee2");
$("#result").append("<hr />");
ee1.bar("ee1");
ee2.bar("ee2");
$("#hola").html("hola hellboy");
ee1.foo("ee1");
ee2.foo("ee2");


Another way to handle this situation, which is useful if you want to call your plugin's methods from elsewhere (perhaps a different file etc.) is to write the plugin logic as a class and then instantiate that class inside the jQuery plugin, storing the instance in $.data.

(function($) {

  var Animal = function(el, settings) {
    this.$el = $(el);
    this.settings = settings;

    this.foo();
  };

  Animal.prototype.eat = function() {
    // Do stuff
    if (this.settings.isVegetarian) {
      console.log('I eat plants');
    } else {
      console.log('I eat meat');
    }
  };

  Animal.prototype.play = function() {
    // Do other stuff but return this.$el so you can maintain chain
    return this.$el;
  };

  // Create jQuery plugin
  var pluginName = 'myPlugin';

  $.fn[pluginName] = function(options) {
    // Defaults
    var settings = $.extend({
      isVegetarian: true,
    }, options );

    return this.each(function() {
      if (!$.data(this, pluginName)) {
        // Store plugin instace with element (this), 
        // so public methods can be called later: 
        // $('.el').data('myPlugin').eat();
        $.data(this, pluginName, new Animal(this, settings));
      }
    });
  };

}(jQuery));

Then when you want to call your plugin, it's just like normal:

$('.dog).myPlugin();

and call a method:

$('.dog').data('myPlugin').eat();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜