0

我正在使用 Electron 创建一个小桌面应用程序并使用module.exports. 在“服务器”端,这工作正常。但是,当我在前端使用 module.exports 时,根据 Electron 文档,我收到此错误。

Uncaught TypeError: this.showProgressbar is not a function"

var ViewController = {
    getPageCount: function (res) {
        this.total = res;
        this.showProgressbar(res);
    },

    showProgressBar: function (num) {
        $('.progress-container').addClass('show');
        $('.progress-bar').style('width', '0%');
    }
};

module.exports = ViewController;

在客户端,这就是我访问此文件的方式。

var view = require(__dirname + '/client/ViewController.js');

ipc.on('page_count', view.getPageCount);

在这种情况下,我应该如何访问内部方法?

4

2 回答 2

2

那是因为当回调被调用时,它是在错误的上下文中被调用的。要绑定上下文,请使用Function.bind

ipc.on('page_count', view.getPageCount.bind(view));
于 2015-07-06T18:05:44.803 回答
2

ViewController 既不是“类”也不是实例,它是一个具有两个属性的纯 JavaScript 对象。

如果您希望它表现得像一个类,并且能够在创建实例时从方法访问其他属性,那么您应该这样做:

var ViewController = function(ipc){
        this.ipc=ipc;
        this.ipc.on('page_count', this.getPageCount);
};

ViewController.prototype.getPageCount: function (res) {
        this.total = res;
        this.showProgressbar(res);
},

ViewController.prototype.showProgressBar: function (num) {
    $('.progress-container').addClass('show');
    $('.progress-bar').style('width', '0%');
}
module.exports = ViewController;

您仍然需要实例化 ViewController :

var ViewController = require(__dirname + '/client/ViewController.js');

var controller = new ViewController(ipc);
于 2015-07-06T18:36:12.033 回答