When passing an object method as a function argument, I have to use `bind' to make sure the context (this) of the method is set correctly. Then there are lots of bind's in my code... Is this the clean way for writing JS code? What is the recommended design pattern for passing methods? Maybe I should pass the entire object, or redesign my object?
Thank you.
For your reference, I pasted my code here. This is definitely not a good code. For example, probably, I may want to use multi-sql-statements rather than calling them one by one.
function insertDB(response, postData) {
var mysql = require('mysql');
var async = require('async');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user',
password : 'pswd',
database : 'mydb',
});
async.series([
connection.connect.bind(connection),
async.apply(connection.query.bind(connection),
"CREATE TABLE IF NOT EXISTS concepts ("+
"name VARCHAR(64) NOT NULL,"+
"priority INT NOT NULL DEFAULT 0,"+
"date DATE NOT NULL,"+
"notes VARCHAR(256),"+
"PRIMARY KEY (name))"),
async.apply(connection.query.bind(connection),
"INSERT INTO concepts VALUES('" +
postData["word"] + "',0,CURDATE(),'')"),
connection.end.bind(connection)
],
function(err, result) {
if (err) console.error(err);
});
}
You can use call or apply to do this, both allow you to set the scope and to pass any args you want. The difference between call and apply is call takes comma seperated arguements such as:connection.connect.call( connection, arg1, arg2, arg2 );
And apply takes an array of args like this:var args = [ arg1, arg2, arg3 ];
connection.connect.apply( connection, args );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With