在 JavaScript 类中创建方法事件

create method event in javascript class

本文关键字:方法 事件 创建 JavaScript      更新时间:2023-09-26

在wapp中.js我在JavaScript中有以下类:

function Wapp() {
    this.page = function($page_name) {
        this.onLoad = function($response) {
        }
    }
    this.navigate = {
        changePage: function(link) {
            // Ajax request to load the page
            $.post(link, {}, function(response) {
                // Code to display the page
            });
        }
    }
}

在应用程序.js脚本中,我有以下代码:

var wapp = new Wapp();

我想这样做:

wapp.page('home').onLoad(function() {
    // doSomething();
}
// When I call the method 'changePage'
wapp.navigate.changePage('home');
// at the end of the page load 'home' I want to call the function 'doSomething()' inside the 'onLoad' method

我应该如何在类中定义方法,以确保在某个操作结束时(在本例中为 ajax 调用结束时)运行在 app.js 中的"onLoad"方法中定义的代码?

您可以在

构造函数时将函数作为变量分配给您的类。稍后您可以在代码中调用分配的函数(例如,在另一个函数的末尾)

https://jsfiddle.net/L8c2s6xr/

function func (functionToCall) {
  this.functionToCall = functionToCall;
  this.doSomething = function () {
    this.functionToCall();
  }
}
var f = new func (
  function() {
    alert('this works');
  }
);
f.doSomething();