博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

jQ的自定义插件

Posted on 2015-03-09 16:46  doncc  阅读(523)  评论(0)    收藏  举报

此文运用的是优雅的Markdown而书

项目中写js时,有很多时候有需要重复利用的东西,我们可以给它们写成一个插件的形式,这样阅读性和适用性都会大大提高。最近抽个时间,好一番的研究了下 Jcrop 的插件,发现它们的代码写的还算比较清晰,所以扒出来研究了一番、记录,以备后面呢利用。研究的不够透彻,还望多多指点 😉

以下是我自己根据源码,总结出来的一份模板,在使用时候根据模板嵌套自己的代码即可。上代码

  • pageplugin.js

      (function ($) {
    
      $.PagePlugin = function (obj, opt) {
    
      var options = $.extend({}, $.PagePlugin.defaults),
          docOffset,
          _ua = navigator.userAgent.toLowerCase(),
          is_msie = /msie/.test(_ua),
          ie6mode = /msie [1-6]\./.test(_ua);
    
      if (typeof (obj) !== 'object') {
          obj = $(obj)[0];
      }
    
      if (typeof (opt) !== 'object') {
          opt = {};
      }
    
      function setOptions(opt) {
          if (typeof (opt) !== 'object') opt = {};
          options = $.extend(options, opt);
      }
    
      //自定义方法,需要在下面api声明
      function setImage(src, callback) {
    
          if (typeof (callback) == 'function') {
              callback.call(api);
          }
      }
    
      setOptions(opt);
      var $orig = $(obj);
    
      //调用内部方法
      ScoreManager.getBo();
      ScoreManager.getCo();
    
      //scoreManager,相当于自定义类
      var ScoreManager = (function () {
          function getScore1(){
              alert("key1");
          }
          
          function getScore2(){
              alert("key2");
          }
    
          return {
              getBo: getScore1,
              getCo: getScore2
          };
    
      }());
    
       //定义api
      var api = {
          setImage: setImage,
          focus:ScoreManager.getBo,
          getBounds: function () {
              return [1, 2];
          }
    
      };
    
      $orig.data('PagePlugin', api);
      return api;
      }
    
      //设置默认属性
      $.PagePlugin.defaults = {
      	marginT: 0,
      	marginL: 0
      };
      }(jQuery));
    
  • 如何使用?

    index.js

      var api = null;
    
      //这里"#page_plugins"我定义为传入控件的内容,可能为id,亦可能class。
    
      api = $.PagePlugin("#page_plugins", {
      marginT: 10,
      marginL: 20
      });
    
      api.getBounds();
      api.setImage("h1", function () {
    
      });