使用AngularJS使用window.bind()类似的功能

时间:2021-12-02 19:17:41

I want to set the context of a function and pass it as a callback. For that I am doing this.

我想设置函数的上下文并将其作为回调传递。为此我正在做这个。

myController.myService.validateToken(param)
    .then( myController.myService.getToken.bind( myController.myService ) );

myController.myService.getToken.bind( myController.myService )

myController.myService.getToken。绑定(myController。myService)

But I am not sure whether it's the right approach or not?

但我不确定这是否是正确的方法?

Does Angular provide similar functionality as bind()?

角度是否提供与bind()类似的功能?

1 个解决方案

#1


2  

Please refer to angular.bind, which is defined in AngularJS 1.4.1 (Line 1146) as:

请参考角。bind在AngularJS 1.4.1(第1146行)中定义为:

function bind(self, fn) {
  var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  if (isFunction(fn) && !(fn instanceof RegExp)) {
    return curryArgs.length
      ? function() {
          return arguments.length
            ? fn.apply(self, concat(curryArgs, arguments, 0))
            : fn.apply(self, curryArgs);
        }
      : function() {
          return arguments.length
            ? fn.apply(self, arguments)
            : fn.call(self);
        };
  } else {
    // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
    return fn;
  }
}

So the usage should be like:

所以用法应该是:

var context, fn, args;
angular.bind(context, fn, args);

#1


2  

Please refer to angular.bind, which is defined in AngularJS 1.4.1 (Line 1146) as:

请参考角。bind在AngularJS 1.4.1(第1146行)中定义为:

function bind(self, fn) {
  var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  if (isFunction(fn) && !(fn instanceof RegExp)) {
    return curryArgs.length
      ? function() {
          return arguments.length
            ? fn.apply(self, concat(curryArgs, arguments, 0))
            : fn.apply(self, curryArgs);
        }
      : function() {
          return arguments.length
            ? fn.apply(self, arguments)
            : fn.call(self);
        };
  } else {
    // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
    return fn;
  }
}

So the usage should be like:

所以用法应该是:

var context, fn, args;
angular.bind(context, fn, args);