【问题标题】:Javascript Module Pattern confusionJavascript 模块模式混淆
【发布时间】:2023-07-04 03:19:01
【问题描述】:

我正在尝试使用 Javascript 模块模式。我希望我的模块有一个可以在加载 json 文件时调用的公共方法。在这个简单的示例中,模块在 init 上加载 json,并且(应该)在调用公共方法 'loadPic' 时将图像加载到 DOM 元素中。图像的来源在 json 文件中。)第一次运行脚本时,出现以下错误: Uncaught TypeError: Cannot read property 'src' of undefined。我的解释是在加载数据之前自动调用方法'loadPic'......但我不知道如何防止这种情况。这是代码(PS:我使用的是Zepto,jQuery的'轻'版本):

<!-- language: lang-js -->
/* in module file: DualG.js */
;(function ($) {
    $.extend($.fn, {
        DualG: function (element, options) {
        var defaults = { // not used yet...
            indexStart:0,
            url: 'js/data.json'
        },
            my = {},
            init,
            loadPic,
            plugin = this;

        plugin.settings = {};
        plugin.pics = [];

        init = function () {
            plugin.settings =  $.extend{}, defaults, options);
            $.getJSON(plugin.settings.url, function (data) {
                var l = data.images.length, i;
                for (i = 0; i < l; i = i + 1) {
                    plugin.pics[data.images[i].index] = data.images[i];
                }
            });

        init();

        my.loadPic = function (index, container) {
            $(container).empty().append($("<img>").attr({"src":plugin.pics[index].src}));
        };

        return my;
     }
  });
}(Zepto));

【问题讨论】:

  • 语法错误...$.extend{}.
  • 嗨 Katspaugh - 感谢您的回答。但是你确定吗?来自 zeptojs.com:创建插件
    可以通过添加方法作为 $.fn 的属性来编写插件:
    ;(function($){ $.extend($.fn, { foo: function() { // this 引用当前的 Zepto 集合。 // 如果可能,返回 Zepto 集合以允许链接。 return this.html('bar') } }) })(Zepto)
  • "当我第一次运行脚本时,我得到以下错误:Uncaught TypeError: Cannot read property 'src' of undefined。我的解释是方法'loadPic'是自动调用的,之前数据已加载......“你为什么这么认为?你调试过你的脚本吗?
  • @AaronKurtzhals - 当我尝试使用此脚本时,我在控制台中收到此错误。我将 dom 上的脚本称为准备就绪。在我自己明确地调用它之前,它似乎调用了方法'loadPic'......
  • 你知道控制台是什么,很好。现在,更进一步,你的控制台应该有这个“中断所有异常”按钮,它可以让你在运行时检查你的代码(它被称为调试)。尝试查看调用堆栈以了解实际发生的情况。 youtu.be/c_oiQYirKuY

标签: javascript design-patterns module zepto


【解决方案1】:

我的问题是数据是同步加载的——所以我想使用尚未加载的数据。加载数据后,我在 init 中添加了一个事件触发器。然后,我监听事件并调用 loadPic 方法...谢谢大家的帮助。

【讨论】: