First of all, you should note that we define all methods on the
prototype
prop-
erty of the
SerialDevice
object. I won’t go into the details here, but you should
know that this is one way to add new methods to objects in JavaScript.
The
connect
method delegates its work to the
chrome.serial.connect
function that
you saw in the previous section already. The only thing worth noting is the
callback function we pass in the function call. Again we use
bind
to set the
callback function’s context explicitly. This way, we make sure that
onConnect-
Complete
has access to the properties of the
SerialDevice
object.
We benefit from that in the
onConnectComplete
method. Here we can set the
con-
nectionId
property of our
SerialDevice
object as soon as we’ve successfully connect-
ed to a serial device. If we hadn’t bound
onConnectComplete
before,
this
would
have a completely different meaning in this function, and we couldn’t access
the properties of the
SerialDevice
object.
In lines 14 and 15, we use the same technique to add receive and error listen-
ers to the
chrome.serial
object. Here we use the listeners we’ve prepared in the
constructor function before. After we’ve established the connection success-
fully, we call the
onConnect
object’s
dispatch
method to spread the good news to
all listeners outside.
Eventually, we have to implement the actual listener functions that deal with
incoming and outgoing data and with errors:
ChromeApps/SerialDevice/js/serial_device.js
SerialDevice.prototype.onReceive = function(receiveInfo) {
if (receiveInfo.connectionId !== this.connectionId) {
return;
}
this.readBuffer += this.arrayBufferToString(receiveInfo.data);
var n;
while ((n = this.readBuffer.indexOf('\n')) >= 0) {
var line = this.readBuffer.substr(0, n + 1);
this.onReadLine.dispatch(line);
this.readBuffer = this.readBuffer.substr(n + 1);
}
};
SerialDevice.prototype.onReceiveError = function(errorInfo) {
if (errorInfo.connectionId === this.connectionId) {
this.onError.dispatch(errorInfo.error);
}
};
SerialDevice.prototype.send = function(data) {
report erratum • discuss
Writing a SerialDevice Class • 277
www.it-ebooks.info