将jQuery插件转换为函数并在现有JavaScript对象

时间:2016-01-02 05:47:28

标签: javascript jquery

下面我有一个JavaScript项目的基本结构,下面是一个小的jQuery插件库。

我的目标是基本将底层jQuery插件集成到我的JavaScript项目中。

在下面的项目代码中,jQuery插件在get_social_counts函数内部被调用。如果jQuery插件可以转换为常规函数并放入项目中,那么可以更新get_social_counts内部对它的调用,只需从同一个对象调用一个函数。

我不知道如何将jQuery插件集成到我的代码中,尽管有任何帮助。

JS库

var SocialShareButtons = {

  init: function() {
    this.getPageDataToShare();
    this.build_social_btn_html();
    this.buildShareWindow();
  },

  get_social_counts: function(thisUrl) {

            $('.sharedCount .count').countTo({
                from: 0,
                to: totalCount,
                speed: 1000,
                refreshInterval: 5,
                formatter: function (value, options) {
                    return value.toFixed(options.decimals);
                },
            });

  },

  ////////////// several other functions.......

}

jQuery插件

  $.fn.countTo = function (options) {
    options = options || {};

    return $(this).each(function () {
      // set options for current element
      var settings = $.extend({}, $.fn.countTo.defaults, {
        from:            $(this).data('from'),
        to:              $(this).data('to'),
        speed:           $(this).data('speed'),
        refreshInterval: $(this).data('refresh-interval'),
        decimals:        $(this).data('decimals')
      }, options);

      // how many times to update the value, and how much to increment the value on each update
      var loops = Math.ceil(settings.speed / settings.refreshInterval),
        increment = (settings.to - settings.from) / loops;

      // references & variables that will change with each update
      var self = this,
        $self = $(this),
        loopCount = 0,
        value = settings.from,
        data = $self.data('countTo') || {};

      $self.data('countTo', data);

      // if an existing interval can be found, clear it first
      if (data.interval) {
        clearInterval(data.interval);
      }
      data.interval = setInterval(updateTimer, settings.refreshInterval);

      // initialize the element with the starting value
      render(value);

      function updateTimer() {
        value += increment;
        loopCount++;

        render(value);

        if (typeof(settings.onUpdate) == 'function') {
          settings.onUpdate.call(self, value);
        }

        if (loopCount >= loops) {
          // remove the interval
          $self.removeData('countTo');
          clearInterval(data.interval);
          value = settings.to;

          if (typeof(settings.onComplete) == 'function') {
            settings.onComplete.call(self, value);
          }
        }
      }

      function render(value) {
        var formattedValue = settings.formatter.call(self, value, settings);
        $self.text(formattedValue);
      }
    });
  };

  $.fn.countTo.defaults = {
    from: 0,               // the number the element should start at
    to: 0,                 // the number the element should end at
    speed: 1000,           // how long it should take to count between the target numbers
    refreshInterval: 100,  // how often the element should be updated
    decimals: 0,           // the number of decimal places to show
    formatter: formatter,  // handler for formatting the value before rendering
    onUpdate: null,        // callback method for every time the element is updated
    onComplete: null       // callback method for when the element finishes updating
  };

  function formatter(value, settings) {
    return value.toFixed(settings.decimals);
  }
}(jQuery));

1 个答案:

答案 0 :(得分:2)

注意到它只是一个更新DOM的计数器,我想你可以重写逻辑。

作为一个jquery插件,这将适用于每个选定的dom元素。使用以下内容,您需要在此处使用循环或修改多个元素的函数本身。

希望以下有帮助...... JS功能:

function countTo(dom, to, from, speed, refreshInterval, todecimals) {

    var loops = Math.ceil(speed / refreshInterval),
        increment = (to - from) / loops,
        loopCount = 0,
        value = from,
        timer;

    if (timer) clearInterval(timer);
    timer = setInterval(updateTimer, refreshInterval);

    render(value);

    function updateTimer() {
        value += increment;
        loopCount++;
        render(value);

        if (loopCount >= loops) {
            clearInterval(timer);
            value = to;
        }
    }

    function render(value) {
        dom.textContent = value.toFixed(todecimals);
    }
}

你可以用:

来调用它
var domElement = $('.sharedCount .count')[0];

countTo(domElement, 0, totalCount, 1000, 5, options.decimals);