开发者

How to addHandler with parameter?

If I try to pass parameter like: this._Click(i) I get an error.

 BBtor = function(element) {
//some code

}   
 BBtor.prototype = {


    initialize: function() {
      for (var i = 0; i < 3; i++) {
       $addHandler($get("Button"+i),'mouseup' , this._Click(i));
      }
    },
    
    _Click: function(param) {
           alert(param);
    }
}

The error I get:

Microsoft JScript runtime error: Sys.ArgumentUndefinedException: Value cannot be undefined. Parameter name: handler

Again. if run this (without parameter), it works:

 $addHandler($g开发者_高级运维et("Button"+i),'mouseup' , this._Click);

if I try this:

 $addHandler($get("Button"+i),'mouseup' , this._Click(i));

it's not working.


This worked for me:

$addHandler($get("Button"+i),'mouseup' , function(xx) { return function() { that._Click(xx) } } (i)); 

But with that I got another problem. how to remove the handler in dispose function?

dispose: function() {             
      for (var i = 0; i < 3; i++) {
     var that = this;
         $removeHandler($get("Button"+i),'mouseup' , function(xx) { return function() { that._Click(xx) } } (i));          

    },

I get error:

Microsoft JScript runtime error: Sys.InvalidOperationException: Handler was not added through the Sys.UI.DomEvent.addHandler method.

Anyway, is it important to remove click events from the buttons?


Okay so, _Click is a function, but _Click(i) is not -- _Click(i) is the value that function returns when you pass in i as a parameter. In this case, _Click(i) is undefined because _Click doesn't contain any return statements. Maybe you want something like this:

var that = this;
$addHandler($get("Button"+i),'mouseup' , function() {that._Click(i)});

Even though i is defined in the outer function, initialize, it's accessible in the inner (anonymous) function, function() {that._Click(i)}.

As for the that = this thing, that's necessary because inside the inner function, the value of this will change (I'm not sure what it will change to in this case, but it probably won't be what you expect). Another way you could do this is simply:

$addHandler($get("Button"+i),'mouseup' , function() {BBtor._Click(i)});


I found this, hope it helps.

Seems that you have to accept two arguments as e is assumed to be there.

var args = new Array();
args[0] = someVariable;
args[1] = someOtherVariable;
$addHandler(button, 'click', Function.createCallback(ButtonClicked, args));

function ButtonClicked(e, args)
{
 Useful code...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜