开发者

Can a click handler be an object?

开发者 https://www.devze.com 2023-04-11 14:38 出处:网络
I\'m trying to register on +1 clicks from within my module, which is wrapped as an annonymous function.

I'm trying to register on +1 clicks from within my module, which is wrapped as an annonymous function.

For this end, I created a global object MyModule, and exported my click handler function through it. The problem is - my click handler doesn't get called.

Live demo. Code:

// Initialize +1 button
gapi.plusone.go();


(function(){
  window.MyModule = {};

  function plusOneClicked() {
    alert("+1!");
  }

  window.MyModule.plusOneClicked = plusOneClicked;
})()

...

<g:plusone callback='window.MyModule.plusOneClicked'></g:plusone>

When I give as a callback an external function, whose only purpose is to forward the calls to win开发者_C百科dow.MyModule.plusOneClicked, it works:

function foo() {
  window.MyModule.plusOneClicked();
}
...
<g:plusone callback='foo'></g:plusone> 

Why would the click handler miss window.MyModule.plusOneClicked(), but find foo()?


Google is probably writing

window[callback]();

in their code.

This requires that the callback string refer to a property of window, not a property of another object.


I believe because callback expects a direct handler method (as in foo()) rather than a reference (as in window.MyModule.plusOneClicked). So basically, you cannot simply assign such a reference to click handler, but write a (wrapper) method as the handler and have it perform the necessary invocation.

0

精彩评论

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