txcotrader
txcotrader

Reputation: 595

Javascript using the YUI library

Is it possible to pass arguments to a function using YUI's .on("click", )? For example here is some code that I'm looking at:

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)
}

I'd like to remove some redundancy by doing something like:

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"));
}

It's my understanding that YUI will pass the "this" object to what ever function is called from .on("click", function).

Thanks for your help.

Upvotes: 0

Views: 141

Answers (2)

Sushant Sudarshan
Sushant Sudarshan

Reputation: 410

You can use JavaScript closures to achieve this. This will also give you more control on the number and type of parameters that you want the event handler to have access to. Also, this method is framework independent.

e.g In the code snippet given in the question, thisTest could perform the closure as follows.

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.

    }
}

Here is a jsFiddle link demonstrating this. http://jsfiddle.net/M98vU/4/

Two things one must keep in mind here are:

  1. Cyclic references caused by attaching event handlers through closures might cause memory leaks in old(ish) browsers. Detaching the handlers when not needed or on page unload might be a good idea.

  2. The fixed / static parameters being passed must be known(determinable) at the time of attaching the handler.

Upvotes: 1

foxxtrot
foxxtrot

Reputation: 11402

You can send a single argument, per the API Docs here: http://developer.yahoo.com/yui/docs/YAHOO.util.Element.html#method_on

For instance:

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");
}

If you wanted to pass multiple values, you'd need to either create an Array or Object that contains all the values you want to pass. This is a limitation in the API.

Upvotes: 2

Related Questions