我如何使用扩展的jQuery函数?

时间:2014-07-27 00:22:17

标签: javascript jquery jquery-plugins

我使用名为ColorPicker的jQuery插件。

我添加的来源是here

因此,我的代码只是$("#some_id").ColorPicker(some_options),正如文档中所示,它运行正常。

但是现在,我想只使用源代码中的一个函数function HexToHSB(),但我不知道如何使用它,因为我不完全理解jQuery插件导入。

我尝试了$.ColorPicker.HexToHSB(),但没有做任何事。

1 个答案:

答案 0 :(得分:1)

您将无法执行此操作,因为这些函数对于ColorPicker模块是私有的,并且您无权访问它们。这就是你如何理解插件的工作原理:

// ColorPicker is an object with public methods, but no access to the private variables and functions in it.
// The function is being invoked at runtime, returning an object
var ColorPicker = function(){
  var privateVariables;
  var privateFunction = function(){...};
  ...
  return {
    publicFunction1 = function(){...},
    publicFunction2 = function(){...},
  }
}();

// jQuery is extended here
$.fn.extend({
    ColorPicker: ColorPicker.publicFunction1,
    ColorPicker: ColorPicker.publicFunction2,
});

有两种方法可以解决您的问题:

  1. 从该jQuery库中复制相关功能并使用它们
  2. 将代码添加到jQuery库以公开私有函数(例如,将自定义函数添加到调用HexToHSB()的第375行,然后在第478行使用此函数扩展jQuery)