【问题标题】:Javascript using the YUI library使用 YUI 库的 Javascript
【发布时间】:2013-03-07 06:25:37
【问题描述】:

是否可以使用 YUI 的 .on("click", ) 将参数传递给函数?例如,这是我正在查看的一些代码:

function foo1() {
  var curObj = this;

    this.foo2 = function() {
         curObj.test = "foo2";
    }

    this.foo3 = function() {
         curObj.test = "foo3";
    }

  // called by
  this.blah = {};
  var blah = this.blah;
  blah['x'] = new YAHOO.widget.Button(x)
  blah['x'].on("click", foo2)

  blah['y'] = new YAHOO.widget.Button(y)
  blah['y'].on("click", foo3)
}

我想通过以下方式消除一些冗余:

function setTest(this, foo) {
  this.test = foo;
}

function foo1() {
  var curObj = this;

  // called by
  this.blah = {};
  var blah = this.blah;
  blah['x'] = new YAHOO.widget.Button(x);
  blah['x'].on("click", thisTest("foo2"));

  blah['y'] = new YAHOO.widget.Button(y);
  blah['y'].on("click", thisTest("foo3"));
}

据我了解,YUI 会将“this”对象传递给从 .on("click", function) 调用的任何函数。

感谢您的帮助。

【问题讨论】:

  • 作为一个无关的说明,你为什么还在使用YUI2?它不再被积极维护,现代的 YUI3 是一个非常优秀的库。

标签: javascript yui


【解决方案1】:

您可以根据此处的 API 文档发送单个参数:http://developer.yahoo.com/yui/docs/YAHOO.util.Element.html#method_on

例如:

function setTest(this, foo) {
  this.test = foo;
}

function foo1() {
  var curObj = this;

  // called by
  this.blah = {};
  var blah = this.blah;
  blah['x'] = new YAHOO.widget.Button(x);
  blah['x'].on("click", thisTest, "foo2");

  blah['y'] = new YAHOO.widget.Button(y);
  blah['y'].on("click", thisTest, "foo3");
}

如果您想传递多个值,您需要创建一个包含您要传递的所有值的数组或对象。这是 API 中的一个限制。

【讨论】:

    【解决方案2】:

    您可以使用 JavaScript 闭包来实现这一点。这也将使您能够更好地控制您希望事件处理程序能够访问的参数的数量和类型。此外,此方法与框架无关。

    例如,在问题中给出的代码 sn-p 中,thisTest 可以按如下方式执行闭包。

    var thisTest = function (arg1, arg2) {
    
        return function () { // handler function
    
            // arg1 and arg2 will be available inside this function.
    
            // also any arguments passed to the handler by the caller will be 
            // available without conflicting with arg1 or arg2.
    
        }
    }
    

    这里有一个 jsFiddle 链接演示了这一点。 http://jsfiddle.net/M98vU/4/

    这里必须记住两件事:

    1. 通过闭包附加事件处理程序引起的循环引用可能会导致旧(ish)浏览器中的内存泄漏。在不需要或在页面卸载时分离处理程序可能是个好主意。

    2. 在附加处理程序时,必须知道(可确定)传递的固定/静态参数。

    【讨论】:

      猜你喜欢
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-20
      相关资源
      最近更新 更多