最新消息: 电脑我帮您提供丰富的电脑知识,编程学习,软件下载,win7系统下载。

将变量绑定到回调函数

IT培训 admin 4浏览 0评论

将变量绑定到回调函数

我的控制器中有一些函数可以调用一些数据库函数。所有这些数据库函数都执行“错误回调”,这意味着如果发生数据库错误,它们会执行单独的回调来处理错误。例:

exports.referralComplete = function(req, res){
    /*getting id etc.*/
    db.startDatabaseConnection(function() {
        db.flagReferralAsDone(id, function(success) {
            db.endDatabaseConnection();
            /*doing stuff on success*/
        }, onError);
    }, onError);

    function onError(err, description) {
        logger.error(description + ": " + err);
        user.pageNotFound(req, res);
    }
}

我有多个与此类似的函数,它们调用不同的数据库函数。问题是我现在已经将onError()复制到每个的范围内,因为我在处理错误时需要req和res变量。我当然可以将res和req传递给数据库函数,然后将它们作为参数传递给错误回调,但我觉得可能有更好的方法。

所以问题是:是否有可能以某种方式将res和req绑定到全局onError回调函数,以某种方式我不必将变量作为参数传递给db函数?

我对node.js和javascript很新,所以如果有更好的方法来处理错误,请告诉我。

回答如下:

绑定很简单!

db.startDatabaseConnection(function(){
  // whatever
}, onError.bind(this, var1, var2));

You can learn more about binding by clicking this awesome link, even though the link is sort of long。

这是一个真正的基本演示

// a function
var something = function (a, b, c) {
  console.log(a, b, c);
};

// a binding of something with 3 defined args
var b = something.bind(null, 1, 2, 3);

// call b
b();
//=> 1 2 3

在幕后,这基本上是正在发生的事情

// ES6
const myBind = (f, context, ...x) =>
  (...y) => f.call(context, ...x, ...y);

// ES5
var myBind = function(fn, context) {
  var x = Array.prototype.slice.call(arguments, 2);
  return function() {
    var y = Array.prototype.slice.call(arguments, 0); 
    return fn.apply(context, x.concat(y));
  };
};

var b = myBind(console.log, console, 1, 2, 3);

b();
// => 1 2 3

b(4,5,6)
// => 1 2 3 4 5 6 

语境?

Context允许您动态更改函数的this。请注意,您只能绑定使用function关键字定义的函数的上下文;箭头函数有一个无法操纵的词汇this。这是为了完整性而显示,但我建议不要使用这种程序。通常最好只使用另一个函数参数而不是依赖于动态函数上下文this。像这样支持上下文切换是为了在JavaScript中启用面向对象的样式。除非你使用这种风格,否则我认为没有理由关注背景。

const getCanvas = (id) =>
  document.getElementById(id).getContext('2d')

const draw = function (canvas, x = 0, y = 0)
{ canvas.beginPath()
  canvas.strokeStyle = this.color             // `this` refers to context!
  canvas.rect(x, y, this.width, this.height)  // `this` refers to context!
  canvas.stroke()
}

// create two contexts
const contextA =
  { color: 'blue', width: 10, height: 10 }
  
const contextB =
  { color: 'green', width: 10, height: 20 }

// bind the draw function to each context and the canvas
const drawA =
  draw.bind(contextA, getCanvas('main'))
  
const drawB =
  draw.bind(contextB, getCanvas('main'))

// call the bound drawing functions normally
// draw three blue squares
drawA(0, 0)
drawA(20, 0)
drawA(40, 0)

// and one green rect
drawB(80, 0)
<canvas id="main"></canvas>

将变量绑定到回调函数

我的控制器中有一些函数可以调用一些数据库函数。所有这些数据库函数都执行“错误回调”,这意味着如果发生数据库错误,它们会执行单独的回调来处理错误。例:

exports.referralComplete = function(req, res){
    /*getting id etc.*/
    db.startDatabaseConnection(function() {
        db.flagReferralAsDone(id, function(success) {
            db.endDatabaseConnection();
            /*doing stuff on success*/
        }, onError);
    }, onError);

    function onError(err, description) {
        logger.error(description + ": " + err);
        user.pageNotFound(req, res);
    }
}

我有多个与此类似的函数,它们调用不同的数据库函数。问题是我现在已经将onError()复制到每个的范围内,因为我在处理错误时需要req和res变量。我当然可以将res和req传递给数据库函数,然后将它们作为参数传递给错误回调,但我觉得可能有更好的方法。

所以问题是:是否有可能以某种方式将res和req绑定到全局onError回调函数,以某种方式我不必将变量作为参数传递给db函数?

我对node.js和javascript很新,所以如果有更好的方法来处理错误,请告诉我。

回答如下:

绑定很简单!

db.startDatabaseConnection(function(){
  // whatever
}, onError.bind(this, var1, var2));

You can learn more about binding by clicking this awesome link, even though the link is sort of long。

这是一个真正的基本演示

// a function
var something = function (a, b, c) {
  console.log(a, b, c);
};

// a binding of something with 3 defined args
var b = something.bind(null, 1, 2, 3);

// call b
b();
//=> 1 2 3

在幕后,这基本上是正在发生的事情

// ES6
const myBind = (f, context, ...x) =>
  (...y) => f.call(context, ...x, ...y);

// ES5
var myBind = function(fn, context) {
  var x = Array.prototype.slice.call(arguments, 2);
  return function() {
    var y = Array.prototype.slice.call(arguments, 0); 
    return fn.apply(context, x.concat(y));
  };
};

var b = myBind(console.log, console, 1, 2, 3);

b();
// => 1 2 3

b(4,5,6)
// => 1 2 3 4 5 6 

语境?

Context允许您动态更改函数的this。请注意,您只能绑定使用function关键字定义的函数的上下文;箭头函数有一个无法操纵的词汇this。这是为了完整性而显示,但我建议不要使用这种程序。通常最好只使用另一个函数参数而不是依赖于动态函数上下文this。像这样支持上下文切换是为了在JavaScript中启用面向对象的样式。除非你使用这种风格,否则我认为没有理由关注背景。

const getCanvas = (id) =>
  document.getElementById(id).getContext('2d')

const draw = function (canvas, x = 0, y = 0)
{ canvas.beginPath()
  canvas.strokeStyle = this.color             // `this` refers to context!
  canvas.rect(x, y, this.width, this.height)  // `this` refers to context!
  canvas.stroke()
}

// create two contexts
const contextA =
  { color: 'blue', width: 10, height: 10 }
  
const contextB =
  { color: 'green', width: 10, height: 20 }

// bind the draw function to each context and the canvas
const drawA =
  draw.bind(contextA, getCanvas('main'))
  
const drawB =
  draw.bind(contextB, getCanvas('main'))

// call the bound drawing functions normally
// draw three blue squares
drawA(0, 0)
drawA(20, 0)
drawA(40, 0)

// and one green rect
drawB(80, 0)
<canvas id="main"></canvas>

与本文相关的文章

发布评论

评论列表 (0)

  1. 暂无评论