javascript类中的共享回调处理程序

Shared callback handler in a javascript class

本文关键字:回调 处理 程序 共享 javascript      更新时间:2023-09-26

当前的点击处理程序。

let db = new DB()
$('#action-searchByPhone').click(() => {
    db.searchByPhone("0400111221", (customers) => {
        console.log(customers)
    })
})

我现在的班级。

我想在这个类中共享成功处理程序的功能,就像我与错误处理程序一样。因此,我可以为各种方法共享成功处理程序。

class DB {
    constructor() {
        this.errorHandler = (tx, error) => console.log(error)
    }
    searchByPhone(phone, callback) {
        let successHandler = (tx, result) => {
            let records = Array.from(result.rows)
            callback(records) // how do I pass this in?
        }
        this.db.transaction((tx) => {
            tx.executeSql('SELECT * FROM customer WHERE phone = ?', [phone], successHandler, this.errorHandler)
        })
    }
}

这是我尝试过的,但正如你所期望的那样,它不起作用。我不确定如何将回调函数传递到成功处理程序中。

class DB {
    constructor() {
        this.successHandler = (tx, result) => {
            let records = Array.from(result.rows)
            callback(records) // how do I pass this in?
        }
        this.errorHandler = (tx, error) => console.log(error)
    }
    searchByPhone(phone, callback) {
        this.db.transaction((tx) => {
            tx.executeSql('SELECT * FROM customer WHERE phone = ?', [phone], this.successHandler, this.errorHandler)
        })
    }
}

在executeSql成功回调中使用匿名箭头函数,该函数调用successshandler,并将callback作为额外参数

class DB {
    constructor() {
        this.successHandler = (tx, result, callback) => {
            let records = Array.from(result.rows)
            callback(records) // how do I pass this in?
        }
        this.errorHandler = (tx, error) => console.log(error)
    }
    searchByPhone(phone, callback) {
        this.db.transaction((tx) => {
            tx.executeSql('SELECT * FROM customer WHERE phone = ?', [phone], (tx, result) => this.successHandler(tx, result, callback), this.errorHandler)
        })
    }
}

我觉得上面的内容可以(应该)写成:

class DB {
    constructor() {
    }
    successHandler(tx, result, callback) {
        let records = Array.from(result.rows);
        callback(records);
    }
    errorHandler(tx, error) {
        console.log(error);
    }
    searchByPhone(phone, callback) {
        this.db.transaction(tx => {
            tx.executeSql('SELECT * FROM customer WHERE phone = ?', [phone], (tx, result) => this.successHandler(tx, result, callback), this.errorHandler)
        });
    }
}

你也可以使用bind,将callback作为第一个参数绑定到successHandler

class DB {
    constructor() {
        this.successHandler = (callback, tx, result) => {
            let records = Array.from(result.rows)
            callback(records) // how do I pass this in?
        }
        this.errorHandler = (tx, error) => console.log(error)
    }
    searchByPhone(phone, callback) {
        this.db.transaction((tx) => {
            tx.executeSql('SELECT * FROM customer WHERE phone = ?', [phone], this.successHandler.bind(this, callback), this.errorHandler)
        })
    }
}