I am learning about javascript modules and how to write them. I ran into the issue that im not 100% sure that my pattern is correct. Any comments that might make it easyer for me later on will be nice, but my problem is im not sure how to use the prototype correctly.
I use my module like this:
var cm = CodeMirror.fromTextArea(document.getElementById("code"), {
lineNumbers: true,
matchBrackets: true,
mode: "text/x-csharp"
});
var adapt = new $.codeMirrorSignalRAdapter(cm, $.connection.codeHub);
but in my adapter.prototype hubChange, the this.silent is undefined. I would like to think that the var adapter = function(cm,hub) is the constructor and i do not know how i access the properties, self.[cm,hub,silent] from the prototype functions.
(function ($, window) {
"use strict";
if (typeof ($) !== "function") {
// no jQuery!
throw new Error("CodeMirrorAdapter: jQuery not found. Please ensure jQuery is referenced before the SignalR.js file.");
}
if (typeof ($.signalR) !== "function") {
throw new Error("CodeMirrorAdapter: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/hubs.");
}
var adapter = function (cm, hub) {
var self = this;
self.cm = cm;
self.hub = hub;
self.silent = false;
cm.on("change", function (_, change) { self.onChange(change); });
hub.client.Change = self.hubChange;
return self;
};
adapter.fn = adapter.prototype = {
init: function (cm, hub) {
},
onChange: function (change) {
if (!this.silent) {
this.hub.server.change(change)
.done(function () { })
.fail(function (ee) { alert(ee) });
}
},
hubChange: function (change) {
alert(this.silent);
this.silent = true;
this.cm.replaceRange(change.text[0], change.from);
this.silent = false;
},
};
$.codeMirrorSignalRAdapter = adapter;
}(window.jQuery, window));
Other than the problem with this keyword, does the module design look somewhat okay?