2013-08-12 44 views
14

Tôi đang cố gắng tìm hiểu cách gọi các hàm trong plugin jQuery của tôi từ bên ngoài plugin. Mã tôi đã thử không hoạt động. Tôi chắc chắn rằng tôi sẽ phải cơ cấu lại plugin của mình để cho phép điều này, nhưng tôi không chắc chắn làm thế nào để. Trong ví dụ này, tôi đang cố truy cập chức năng underline().Gọi một hàm bên trong một plugin jQuery từ bên ngoài

jsFiddle

jQuery plugin

(function($) { 
    "use strict"; 

    $.fn.testPlugin = function(options) { 

     // Settings 
     var settings = $.extend({ 
      newText : "Yabadabado" 
     }, options); 

     return this.each(function(i, el) {    

      var init = function(callback) { 
       if($(el).attr("class") === "red") { 
        $(el).css("color","red"); 
       } 

       $(el).text(settings.newText); 

       if(callback && typeof(callback) === "function") { 
        callback(); 
       } 
      }; 

      var underline = function() { 
       $(el).addClass("underline"); 
      }; 

      init(); 
     }); 
    }; 

}(jQuery)); 

Gán các plugin để selectors

var doTest = $("#testItem").testPlugin({ 
    newText: "Scoobydoo" 
}); 

var doNewTest = $("#newTestItem").testPlugin({ 
    newText: "kapow!" 
});  

Gọi một hàm nằm trong các plugin

$("#underline").click(function(e) { 
    e.preventDefault(); 
    doTest.underline(); 
}); 
+0

bạn không thể làm gọi hàm như vậy. 'underline' là một hàm bên trong, do đó bạn cần tạo một phương thức để có thể gọi hàm đó. – putvande

Trả lời

25

Hãy xem closures.

Dưới đây là ví dụ cơ bản về hình thức đóng của một plugin jQuery.

$.fn.plugin = function() { 

    return { 
     helloWorld: function() { 
      console.log('Hello World!'); 
     } 
    } 
}; 

// init plugin. 
var test = $('node').plugin(); 

// call a method from within the plugin outside of the plugin. 
test.helloWorld(); 

Bạn có thể xem ví dụ khác tại jsfiddle sau đây.

http://jsfiddle.net/denniswaltermartinez/DwEFz/

+0

Tôi có truy vấn nếu 'helloworld' không có trong' return'? –

+0

@ shyammakwana.me Sau đó, bạn không thể truy cập nó bên ngoài phạm vi đóng (trong trường hợp này là plugin). –

14

Điều đầu tiên đầu tiên chúng ta cần phải hiểu từng bước trong việc xây dựng một plugin jQuery, như xây dựng nó một plugin javascript (lớp) nhưng chúng tôi có thêm vào nó một lớp jQuery.

//We start with a function and pass a jQuery class to it as a 
//parameter $ to avoid the conflict with other javascript 
//plugins that uses '$ as a name 
(function($){ 
    //We now append our function to the jQuery namespace, 
    //with an option parameter 
    $.fn.myplugin = function(options) { 
     //the settings parameter will be our private parameter to our function 
     //'myplugin', using jQuery.extend append 'options' to our settings 
     var settings = jQuery.extend({ 
      param:'value', 
     }, options); 
     //Define a reference to our function myplugin which it's 
     //part of jQuery namespace functions, so we can use later 
     //within inside functions 
     var $jquery=this; 

     //Define an output object that will work as a reference 
     //for our function 
     var output={ 
      //Setup our plugin functions as an object elements 
      'function1':function(param){ 
       //Call jQuery reference that goes through jQuery selector 
       $jquery.each(function(){ 
        //Define a reference of each element of jQuery 
        //selector elements 
        var _this=this; 
       }); 
       //This steps is required if you want to call nested 
       //functions like jQuery. 
       return output; 
      }, 
      //If we want to make our plugin to do a specific operations 
      //when called, we define a function for that 
      'init':function(){ 
       $jquery.each(function(){ 
        var _this=this; 
        //Note that _this param linked to each jQuery 
        //functions not element, thus wont behave like 
        //jQuery function. 
        //And for that we set a parameter to reference the 
        //jQuery element 
        _this.$this=$(this); 

        //We can define a private function for 'init' 
        //function 
        var privatefun=function(){} 
        privatefun(); 

        //We can now do jQuery stuffs on each element 
        _this.$this.on('click',function(){ 
         //jQuery related stuffs 
        }); 
       }); 
       //We can call whatever function we want or parameter 
       //that belongs to our plugin 
       output.function1("value"); 
      } 
     }; 
     //Our output is ready, if we want our plugin to execute a 
     //function whenever it called we do it now 
     output.init(); 

     //And the final critical step, return our object output to 
     //the plugin 
     return output; 
    }; 
//Pass the jQuery class so we can use it inside our plugin 'class' 
})(jQuery); 

Sử dụng chức năng của chúng tôi bây giờ rất dễ dàng

<div class="plugintest"> 
    <span>1</span> 
    <span>2</span> 
    <span>3</span> 
    <span>4</span> 
</div> 

<script> 
    $(function(){ 
     var myplugin=$(".plugintest > span").myplugin({ 
      param:'somevalue' 
     }); 
     myplugin.function1(1).function1(2).function1(3); 
    }); 
</script> 

Nói tóm lại, các plugin jQuery và bất kỳ plugin javascript chỉ đơn giản là về phạm vi các thông số.

Fiddle phiên bản https://jsfiddle.net/eiadsamman/a59uwmga/

Các vấn đề liên quan