0

I'm using Electron to create a little desktop app and exporting with module.exports. On the 'server' side this works fine. However, when I'm using module.exports on the front end, as per Electron docs, I get this error.

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;

On the client side, this is how I'm accessing this file.

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

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

How should I be accessing internal methods in this instance?

Chris R.
  • 699
  • 8
  • 23

2 Answers2

2

That's because when the callback is being called, it's being called in the wrong context. To bind the context, use Function.bind.

ipc.on('page_count', view.getPageCount.bind(view));
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
2

ViewController is neither a 'Class' nor an instance, its a plain javascript object with two properties.

If you want it to behave like a class and be able to acccess to other properties from a method when creating an instance this is how you should do:

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;

You still need to instantiante ViewController :

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

var controller = new ViewController(ipc);
nfleury
  • 165
  • 1
  • 5