【问题标题】:Namespaced jQuery plugins in separate files?命名空间的jQuery插件在单独的文件中?
【发布时间】:2012-02-02 08:12:13
【问题描述】:

我正在构建一个高级图表 API(在 d3 之上)作为 jQuery 插件的集合。

我想将整个项目命名为“d3charts”,但将每个插件都放在自己的文件中。因此,例如,我可能有 d3charts.histogram.js 和 d3charts.pie.js。我希望 API 看起来像这样:

<script src="jquery.js"></script>

// I don't really have any common functionality yet, this is an empty file
// not sure if this sort of thing is necessary to achieve the API below
<script src="d3charts.js"></script>

// load only the chart types I want to actually use
<script src="d3charts.histogram.js"></script>
<script src="d3charts.pie.js"></script>
<script>
    var foo_data = [ ... ];
    var bar_data = [ ... ];
    $('.foo').d3charts.histogram(foo_data);
    $('.bar').d3charts.pie(bar_data);
</script>

我有单独的图表作为常规(非命名空间)jQuery 插件工作,请参阅 sourcepretty display

我的插件需要什么结构才能使这个 API 按我想要的方式工作?这意味着:

// Not this
$('.foo').d3charts().histogram(foo_data);

// Not this either
$.d3charts.pie('.foo', bar_data);

// but chaining should still work:
$('.foo').d3charts.histogram(foo_data).toggleClass('histogramchart');

其他必备素质:

  • 我不能假设加载插件的任何顺序。
  • 理想情况下,我想要一个不需要加载像d3charts.js 这样的空命名空间“父”脚本的解决方案。
  • 在原始(非命名空间)插件中,我使用推荐的return this.each() 在选择器中的每个元素上运行我的代码。命名空间插件应该以某种方式保留这种行为。

This SO 答案似乎是一个难题,但我没有运气将整个图片放在一起。

感谢您的指导!

【问题讨论】:

    标签: javascript jquery


    【解决方案1】:

    每个文件都应该检查jQuery.fn.d3charts是否存在,如果不存在则创建它;否则添加到对象中。

    // Include this in all your files
    if (typeof jQuery.fn.d3charts !== "object") {
        jQuery.fn.d3charts = {};
    }
    // End inclusion
    
    jQuery.fn.d3charts.histogram = function () {
    
    };
    

    这是非常严格的对象检查;如果您只想检查一个真实值(因为它很酷,而且现在每个人都在使用||),请尝试;

    jQuery.fn.d3charts = jQuery.fn.d3charts || { };
    

    【讨论】:

    • 好的——这看起来很明智而且很棒。我的下一行将类似于 return this.each(function() {...}),但现在这是直方图,它不是 jQuery 对象。对于这种情况,我该怎么办?
    • 删除了接受的答案,因为这个解决方案实际上并没有把我带到目标。
    【解决方案2】:

    个人不喜欢臃肿的 jQuery 命名空间,因此我更喜欢将其实现为:

    <script>
    $.namespace = $.namespace || {};
    </script>
    

    使用此方法,您可以为每个文件定义需要定义的内容,最终得到与我刚刚在 jsFiddle 上为您发布的内容类似的内容:jsFiddle example

    【讨论】:

    • 这很可爱,但它没有实现请求的 API。
    【解决方案3】:

    我无法在 SO 或其他地方找到解决方案。我有一种强烈的感觉,没有一种解决方案可以满足我所有的 API 需求。

    我发现的最佳解决方案是将插件打包为 jQuery UI 小部件。你可以在d3charts github repo看到结果。

    【讨论】:

      猜你喜欢
      • 2012-03-02
      • 1970-01-01
      • 1970-01-01
      • 2012-12-04
      • 2012-09-19
      • 2012-06-06
      • 2020-04-20
      • 2012-02-21
      • 1970-01-01
      相关资源
      最近更新 更多