I'm building a menu module. In the first file, slideout.js, I'm creating an object which has a prototype with methods toggle, open and close.
In the second file I'm trying to use that menu-module to access those methods on it's prototype, through jquery event handlers.
The problem is, that "this" in menu.toggle will now refer to the jquery object instead of the object. I understand all that.
My question is, what's the best way to solve this?
It works when doing menu.toggle.bind(menu)
, but that seems wrong. I could also solve it by creating an anonymous function, and then calling menu.toggle. But that seems equally wrong.
My gut says, I should fix this in slideout.js.
slideout.js
'use strict';
var proto = {
isOpen: false,
toggle: function() {
return this.isOpen ? this.close() : this.open();
},
open: function() {
this.isOpen = true;
return this;
},
close: function() {
this.isOpen = false;
return this;
}
};
module.exports = function(options) {
var obj = Object.create(proto);
return obj;
};
main.js
'use strict';
var slideout = require('./slideout'),
$ = global.jQuery;
module.exports = function() {
var menu = slideout();
$('.js-main-menu-trigger').on('click', menu.toggle);
};