2016-10-02 194 views
1

如何從外部覆蓋以下jQuery示例插件代碼的方法。無法覆蓋jquery插件的方法

//This is simplified skeleton of infinatescroll plugin. 
    (function ($) 
    { 
     var defaults = { 
      prop: 'name' 
     }; 

     var methods = { 
      init: function (params) 
      { 
       //Some code 
       return this; 
      }, 
      retrive: function() 
      { 
       console.log('Inside Plugin'); 
       return this; 
      } 
     }; 

     $.fn.my_plugin = function() 
     { 
      //Some code 
      return methods.retrieve.apply(this, arguments); 
     }; 

    })(jQuery); 

我想覆蓋'retrive'方法如下,但它不工作。

(function() 
{ 
    var originalPlugin=$.fn.my_plugin; 
    $.fn.my_plugin.retrive = function() 
    { 
     console.log('Outsite Plugin'); 
    }; 

    originalPlugin.apply(this,arguments); 

    $('body').my_plugin(); 

})(); 

回答

0

你能買得起這樣的東西嗎?

<script type="text/javascript"> 
    //This is simplified skeleton of infinatescroll plugin. 
    (function ($) 
    { 

     var defaults = { 
      prop: 'name' 
     }; 

     var methods = { 
      init: function (params) 
      { 
       //Some code 
       return this; 
      }, 
      retrive: function() 
      { 
       console.log('Inside Plugin'); 
       return this; 
      } 
     }; 

     $.fn.getObj = function(){ 
      return methods; 
     }; 

     $.fn.my_plugin = function() 
     { 
      //Some code 
      return methods.retrive.apply(this, arguments); 
     }; 


    })(jQuery); 

    $(document).ready(function(){ 
     var originalPlugin=$.fn.my_plugin; 
     console.log($.fn.getObj()); 
     $.fn.getObj().retrive = function(){ 
      console.log("look I am changed"); 
     } 


     $('body').my_plugin(); 
    }); 
</script>