it to the
bind
method.
bind
creates a new function and sets the new function’s
this
keyword to the value you passed to
bind
originally. Using
bind
, you can
define a function now, but make sure that it has a certain context when you
actually call it.
When working with event handlers, this is often necessary. Users of the
Seri-
alDevice
class should be able to pass their own callback functions, but they
should be executed in the class’ context. You’ll see how this works in a minute.
At the end of the constructor, we define three instance variables that are all
instances of the
chrome.Event
class.
10
This class provides some nice features to
define and dispatch events within Chrome apps. We use it to define the three
events that users of our
SerialDevice
class can listen for. Now users can register
for
readLine
events using the
onReadLine
property.
The next three methods of the
SerialDevice
class implement everything needed
for connecting and disconnecting serial devices:
ChromeApps/SerialDevice/js/serial_device.js
SerialDevice.prototype.connect = function() {
Line 1
chrome.serial.connect(
-
this.path,
-
{ bitrate: this.baudRate },
-
this.onConnectComplete.bind(this))
5
};
-
-
SerialDevice.prototype.onConnectComplete = function(connectionInfo) {
-
if (!connectionInfo) {
-
console.log("Could not connect to serial device.");
10
return;
-
}
-
this.connectionId = connectionInfo.connectionId;
-
chrome.serial.onReceive.addListener(this.boundOnReceive);
-
chrome.serial.onReceiveError.addListener(this.boundOnReceiveError);
15
this.onConnect.dispatch();
-
};
-
-
SerialDevice.prototype.disconnect = function() {
-
if (this.connectionId < 0) {
20
throw "No serial device connected.";
-
}
-
chrome.serial.disconnect(this.connectionId, function() {});
-
};
-
10.
https://developer.chrome.com/extensions/events
Appendix 4. Controlling the Arduino with a Browser • 276
report erratum • discuss
www.it-ebooks.info