使用goog.events.listen传递参数

时间:2012-11-27 11:53:27

标签: javascript events click google-closure google-closure-library

我正在使用Google Closure的事件处理:

goog.events.listen(this.contentElement, goog.events.EventType.CLICK, this.openEditor);

但是我需要将一个字符串作为参数传递给函数this.openeditor

我查看了文档,但似乎无法解决如何执行此操作,任何人都有任何想法?

谢谢!

2 个答案:

答案 0 :(得分:8)

尝试使用goog.partial,如下所示:

goog.events.listen(this.contentElement, goog.events.EventType.CLICK, goog.partial(this.openEditor,'the string you want to pass it'));

点击this.contentElement后,系统会调用this.openEditor。第一个参数是字符串,第二个参数是事件对象。

答案 1 :(得分:2)

Joshua的回答是正确的 - 只想添加更多信息。

base.js中定义的

goog.bind vs goog.partial

在goog.partial中,上下文被设置为当前上下文 - 它返回一个在当前上下文中执行的函数。

goog.partial = function(fn, var_args) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function() {
    // Clone the array (with slice()) and append additional arguments
    // to the existing arguments.
    var newArgs = args.slice();
    newArgs.push.apply(newArgs, arguments);
    return fn.apply(this, newArgs);
  };
};

goog.bind(实际上检查bind的本机实现)的位置,你可以将上下文作为第二个参数传递

goog.bind = function(fn, selfObj, var_args) {
  //defined in base.js  
  ....
  ....
  return function() {
    return fn.apply(selfObj, arguments);
  };

}