0Pricing
jQuery Academy · 课时

集成公共方法与回调

为插件添加公共方法以支持外部交互,并加入回调函数,让用户能够接入特定的插件事件。

集成公共方法与回调 是 CoddyKit 上的免费 jQuery Academy 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 jQuery Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 jQuery Academy 课程共包含 3 节课。

与您的插件交互

优秀的插件不只是独立运行的工具,还应允许用户在初始化后与其交互!本课将教您如何添加用于外部控制的公共方法,以及用于自定义响应的回调函数。

  • 公共方法:用户可以在插件实例初始化后调用的函数。
  • 回调函数:插件内部发生特定事件时运行的函数。

重新了解插件基础

请回忆一下,jQuery 插件通常会封装在立即调用函数表达式(IIFE)中,以防止污染全局作用域。这种结构为插件逻辑和内部变量提供了安全的存放空间。

我们将在这个熟悉的模式基础上继续构建。

(function($) {
  $.fn.myPlugin = function(options) {
    // Default settings
    var settings = $.extend({}, $.fn.myPlugin.defaults, options);

    return this.each(function() {
      var $this = $(this); // The element the plugin is applied to
      // Plugin logic goes here
      console.log("Plugin initialized on: " + $this.attr('id'));
    });
  };

  // Default options
  $.fn.myPlugin.defaults = {
    message: "Hello from plugin!"
  };
})(jQuery);

// How to use (in HTML <div id="myElement"></div>):
// $('#myElement').myPlugin();

什么是公共方法?

公共方法是插件对外公开的函数。即使插件已经在某个元素上完成初始化,也可以从其内部作用域之外调用该函数。

您可以把它想象成插件的遥控器。您可以让它执行“重置”“更新”或“获取值”等操作。

实现公共方法

要添加公共方法,我们通常会使用 jQuery 的 .data() 方法,将插件实例数据(包括其方法)直接存储在 DOM 元素上。

让我们创建一个简单的“计数器”插件,并添加一个 getValue 方法。

(function($) {
  $.fn.counterPlugin = function(options) {
    var settings = $.extend({
      initialValue: 0
    }, options);

    return this.each(function() {
      var $this = $(this);
      var value = settings.initialValue;

      var methods = {
        getValue: function() {
          return value;
        },
        increment: function() {
          value++;
          $this.text(value); // Update display
        },
        init: function() {
          $this.text(value); // Initial display
        }
      };

      // Store methods on the element's data
      $this.data('counterPlugin', methods);
      methods.init(); // Initialize display
    });
  };
})(jQuery);

// HTML: <div id="myCounter"></div>
// Usage: $('#myCounter').counterPlugin();
// Later: $('#myCounter').data('counterPlugin').getValue();

调用公共方法

插件完成初始化且其方法通过 .data() 存储后,您就可以直接访问并调用这些方法。

关键是先从元素中取出已存储的实例,然后在该实例上调用方法。

// Assume counterPlugin from previous scene is loaded

// HTML: <div id="myCounter"></div>

$(document).ready(function() {
  // Initialize the plugin
  $('#myCounter').counterPlugin({ initialValue: 5 });

  // Get the plugin instance
  var counterInstance = $('#myCounter').data('counterPlugin');

  // Call public methods
  console.log("Current value: " + counterInstance.getValue());
  counterInstance.increment();
  console.log("After increment: " + counterInstance.getValue());
});

什么是回调函数?

回调函数是您传递给插件的函数,插件会在其生命周期中的特定时间点或某些内部事件发生时执行这些函数。

它们允许用户“接入”插件的行为,在不修改插件源代码的情况下添加自己的自定义逻辑。

  • 您可以将它们想象成用于监听插件内部操作的事件监听器。
  • 常见的回调函数:onInit、onChange、onComplete。

实现回调函数

要实现回调函数,首先要在插件的默认选项中定义它。然后,在插件内部,只需在相关事件发生时调用这个函数,并传入有用的数据。

让我们为计数器插件扩展一个 onChange 回调函数。

(function($) {
  $.fn.counterPlugin = function(options) {
    var settings = $.extend({
      initialValue: 0,
      onChange: function(newValue) {} // Default empty callback
    }, options);

    return this.each(function() {
      var $this = $(this);
      var value = settings.initialValue;

      var methods = {
        getValue: function() {
          return value;
        },
        increment: function() {
          value++;
          $this.text(value);
          // Call the callback when value changes
          settings.onChange.call($this[0], value); 
        },
        init: function() {
          $this.text(value);
        }
      };

      $this.data('counterPlugin', methods);
      methods.init();
    });
  };
})(jQuery);

// Usage: See next scene!

传递回调函数

用户在初始化插件时,可以直接在插件的选项对象中传入自定义回调函数。之后,插件会在适当的时间调用这些函数。

请注意,这里使用了 .call($this[0], value)。它会将回调函数内部的 this 设置为 DOM 元素,并将新值作为参数传入。

// Assume counterPlugin with onChange callback is loaded

// HTML: <div id="myCounter"></div>

$(document).ready(function() {
  $('#myCounter').counterPlugin({
    initialValue: 10,
    onChange: function(newValue) {
      console.log("Counter changed to: " + newValue + " on element: " + this.id);
      if (newValue % 2 === 0) {
        $(this).css('color', 'blue');
      } else {
        $(this).css('color', 'red');
      }
    }
  });

  var counterInstance = $('#myCounter').data('counterPlugin');
  counterInstance.increment(); // Triggers callback
  counterInstance.increment(); // Triggers callback
});

多个方法和回调函数

您可以在插件中定义多个公共方法以及多个不同的回调函数,以处理各种事件。这样可以创建灵活且功能强大的组件。

  • 公共方法让用户能够控制插件。
  • 回调函数让插件能够将发生的情况通知用户代码。
(function($) {
  $.fn.advancedCounter = function(options) {
    var settings = $.extend({
      initial: 0,
      onIncrement: null, // New callback
      onDecrement: null, // New callback
      onReset: null      // New callback
    }, options);

    return this.each(function() {
      var $this = $(this);
      var value = settings.initial;

      var methods = {
        getValue: function() { return value; },
        increment: function() {
          value++;
          $this.text(value);
          if ($.isFunction(settings.onIncrement)) {
            settings.onIncrement.call($this[0], value);
          }
        },
        decrement: function() {
          value--;
          $this.text(value);
          if ($.isFunction(settings.onDecrement)) {
            settings.onDecrement.call($this[0], value);
          }
        },
        reset: function() {
          value = settings.initial;
          $this.text(value);
          if ($.isFunction(settings.onReset)) {
            settings.onReset.call($this[0], value);
          }
        },
        init: function() { $this.text(value); }
      };

      $this.data('advancedCounter', methods);
      methods.init();
    });
  };
})(jQuery);

// HTML: <div id="myAdvancedCounter"></div>
$(document).ready(function() {
  $('#myAdvancedCounter').advancedCounter({
    initial: 100,
    onIncrement: function(v) { console.log("Inc: " + v); },
    onReset: function(v) { console.log("Reset to: " + v); }
  });
  var inst = $('#myAdvancedCounter').data('advancedCounter');
  inst.increment();
  inst.reset();
});

公共方法和回调函数提示

设计插件的公共接口时,请牢记以下提示:

  • 命名一致:为方法和回调函数使用清晰且具有描述性的名称。
  • 错误处理:调用回调函数前,检查它们是否确实是函数(例如:$.isFunction(settings.onComplete))。
  • 上下文:使用 .call() 或 .apply() 设置回调函数的 this 上下文,通常将其设置为应用插件的元素。
  • 参数:向回调函数传递相关数据(例如新值、事件对象)。

插件交互测验

请考虑一个在 #myElement 上初始化的 jQuery 插件。该插件有一个名为 doSomething() 的公共方法和一个 onComplete 回调函数。

哪段代码能够在初始化时正确调用公共方法并传递自定义回调函数?

回顾与后续步骤

您已经掌握了如何让 jQuery 插件真正具备交互性和灵活性!

  • 公共方法允许外部代码在插件初始化后对其进行控制和查询。
  • 回调函数为用户提供了注入自定义逻辑的入口,以响应插件内部事件。

这些技术对于构建健壮、可复用且便于用户使用的 jQuery 插件至关重要。

常见问题解答

「集成公共方法与回调」课时是免费的吗?

是的 — 「集成公共方法与回调」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 jQuery Academy 课程的其余内容,请升级到 CoddyKit PRO。 jQuery Academy 课程共包含 3 节课。

「集成公共方法与回调」这节课中我会学到什么?

为插件添加公共方法以支持外部交互,并加入回调函数,让用户能够接入特定的插件事件。 你通过在浏览器中直接运行的动手代码来练习 jQuery Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 jQuery Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 jQuery Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。

「集成公共方法与回调」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 jQuery Academy 课中编写并运行代码吗?

能。每节 jQuery Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 插件设计模式与作用域
  2. 构建可配置且可复用的插件
  3. 集成公共方法与回调
← 返回 jQuery Academy