开发者

How do you pass a parameter to a function when that function is assigned using observe?

I have about 12 div elements in a class called "item"

i have used for-loop to attach a onClick javascript function to each one of them:

for(var i = 0; i < $$(".item").length; i++){
    $$(".item")[i].observe("click", detailPopup);
}

so if I click any of the elements that are of "item" class, it'll run "detailPopup" function. But I want to pass a parameter to that function. More specifically, I want "this"() to be passed.

How do I do that??

I think I made my question as specific as possible, but in case I didn't, let me开发者_高级运维 know, and I'll clarify my question.

THANKS!


Although I haven't explicitly tried this myself I believe you should be able to burn in your parameters.

$$('.item').invoke('observe', 'click', detailPopup.curry(this));

A reference to this will then be passed before all other parameters. Your function might look something like the following...

function detailPopup(parent, event)
{
    ...

The original meaning of this is preserved for the handler's scope, that of the triggered element. Also I used invoke to avoid all that messing around with index values and anonymous functions and stuff.


You can bind this to the function:

for(var i = 0; i < $$(".item").length; i++){
    $$(".item")[i].observe("click", detailPopup.bind(this));
}

JSFiddle Example


You'll want to create an anonymous function. In place of detailPopup, you should put something like: function() { detailPopup(that); }

What is that? Because the value of this isn't transferred to nested functions, you need to assign it to a variable before you can use it. Example: var that = this;

var that = this;

for(var i = 0; i < $$(".item").length; i++){
   $$(".item")[i].observe("click", function() { detailPopup(that); });
}


You can do it like this:

for(var i = 0; i < $$(".item").length; i++){
    (function(t){
        $$(".item")[i].observe("click", function { detailPopup(t); });
    })(this);
}

the (function(t){ ... })(this); is a closure which ensures that this is the correct this otherwise you will get scoping issues. This is important in a few situations, for loops being one of them. If you didnt have a for loop you could have done this:

$$(".item")[i].observe("click", function { detailPopup(someParameter); });
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜