无法读取undefined的功能

时间:2018-03-15 17:18:26

标签: jquery function events plugins undefined

我试图创建另一个扩展$ .event.special对象的事件类型。因为我需要更改与输入类型不同的元素。问题是,当我启动页面时,控制台会给我这个错误:

main.js:5未捕获的TypeError:无法读取属性' mutationLists'未定义的

脚本是这样的:

(function($){

 $.event.special.changeElement = {
    eventType: 'changeElement',
    mutationObserver : new MutationObserver($.event.special.changeElement.mutationsLists),

    setup: function(data, namespaces) {
      var config = { attributes: true, childList: true };
      $.event.special.changeElement.mutationObserver.observe(this, config);
    },

    teardown: function(namespaces) {
      $.event.special.changeElement.mutationObserver.disconnect();
    },

    handler: function(event) {
      event.type = $.event.special.changeElement.eventType;
      return $.event.dispatch.apply(this, arguments);
    },

    mutationsLists : function(mutationsList) {
      for(var mutation of mutationsList) {
          if (mutation.type == 'childList') {
              console.log('A child node has been added or removed.');
          }
          else if (mutation.type == 'attributes') {
              console.log('The ' + mutation.attributeName + ' attribute was modified.');
          }
      }
    }

  }

})(jQuery);

我检查了它,看起来定义了$ .event.special.changeElement,但在调用其成员时看起来未定义...

1 个答案:

答案 0 :(得分:0)

mutationLists$.event.special.changeElement的属性,是一个函数。将属性作为对象的函数充当函数表达式,这意味着在到达代码之前不会定义它。有关此示例,请参阅此jsFiddle

你会在那个小提琴中看到firstFunction可以调用secondFunction,因为它是在它之前定义的。但是,secondFunction无法调用thirdFunction,因为在firstFunction被调用之前未定义它。

要更正您的问题,请在定义属性mutationLists之前定义函数mutationObserver

相关问题