我目前正在使用 BLE https://github.com/evothings/cordova-ble 库使用 Ionic 2 开发应用程序。我在这里想知道的是,我有一个函数 connectToDevice ,它调用函数 ble.connectToDevice ,而函数 ble.connectToDevice 又调用函数 onConnected 。在函数 onConnected 内部,我想调用函数 connectToDevice 外部的函数 enableNotification(device)。但我收到错误:TypeError: _this.enableCoinNotification is not a function.
有人可以解决这个问题并向我解释一下吗?
export class BleProvider {
constructor(){
this.connectToDevice(device)
}
connectToDevice(device){
let onConnected = (device) => {
console.log("Connected to device: " + device.name);
return startNotifications(device);
},
onDisconnected = (device) => {
console.log('Disconnected from device: ' + device.name);
},
onConnectError = (error) => {
console.log('Connect error: ' + error);
};
setTimeout(() => {
ble.connectToDevice(
device,
onConnected,
onDisconnected,
onConnectError)
}, 500);
let startNotifications = (device) => {
console.log("Start Notification called");
this.enableCoinNotification(device) // ERROR : TypeError: _this.enableCoinNotification is not a function
};
}
enableCoinNotification(device){
let onNotificationSuccess = (data) =>{
console.log('characteristic data: ' + ble.fromUtf8(data));
},
onNotificationError = (error) =>{
};
ble.enableNotification(
device,
this.coinEventNotificationUUID,
onNotificationSuccess,
onNotificationError)
}
}
最佳答案
添加bind API:
let startNotifications = (device) => {
console.log("Start Notification called");
this.enableCoinNotification(device);
};
startNotifications.bind(this); // <-- Add this line
当您仅传递由箭头函数定义的函数定义时,this
将会丢失。
或者:
是的,我同意@Junior
ble.connectToDevice(device,
(...arg) => onConnected(...arg),
(...arg) => onDisconnected(...arg),
(...arg) => onConnectError(...arg));
通过更改箭头函数的回调,您可以引用父 this
对象范围。
关于javascript - Ionic 2内部函数和外部函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44776532/