jquery javascript-回调中无法识别的函数

kkih6yb8  于 11个月前  发布在  jQuery
关注(0)|答案(3)|浏览(182)

我正在用jQuery开发一个Cordova应用程序。
在我的index.js中,我有以下代码:

$(document).ready(function() {
   console.log("ready");

   // Initialize the app
   app.initialize();

});

// Define the app
var app = {
    // Initialize the app    
    initialize: function() {
       // deviceready Event Handler
      $(document).on('deviceready', function() {
         console.log("Device is ready!");

         // 'deviceready' is an DOM element on the Html page.
         this.receivedEvent('deviceready');
      });
    },

    // Update DOM on a Received Event
   receivedEvent: function(id) {
      var parentElement = document.getElementById(id);
      var listeningElement = parentElement.querySelector('.listening');
      var receivedElement = parentElement.querySelector('.received');

      listeningElement.setAttribute('style', 'display:none;');
      receivedElement.setAttribute('style', 'display:block;');
   },

...
}

字符串
当我在Cordova中运行脚本时,它抛出了一个错误:

TypeError: this.receivedEvent is not a function


似乎“this”对象没有被正确引用为app。

cld4siwp

cld4siwp1#

你也可以像下面这样做。

initialize: function() {
   // deviceready Event Handler
  var self = this
  $(document).on('deviceready', function() {
     console.log("Device is ready!");

     // 'deviceready' is an DOM element on the Html page.
     self.receivedEvent('deviceready');
  });
},

字符串

tvokkenx

tvokkenx2#

因为thisdeviceready处理函数中是不同的。使用箭头函数:

$(document).on("deviceready", () => {...});

字符串
或者只是避免在函数中初始化事件侦听器--最好在脚本的顶部一次性完成。

vql8enpb

vql8enpb3#

你也可以这样做

const myObject = {
      initialize: function() {
        // deviceready Event Handler
    document.addEventListener('deviceready', () => {
      console.log("Device is ready!");

      // 'deviceready' is a DOM element on the HTML page.
      this.receivedEvent('deviceready');
    });
  },

  receivedEvent: function(event) {
    // Your logic for handling the 'deviceready' event
    console.log(`Received event: ${event}`);
  }
};

// Call the initialize function to start the process
myObject.initialize();

字符串

相关问题