Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how would i declare a 'monkey patched' prototype in typescript

I'm creating a d.ts file for webgl-utils.js from google

I have a problem with one of the last lines where a method in a global object is 'monkey patched' (I think this is the right terminology)

The problem line reads:

 /**
  * Provides requestAnimationFrame in a cross browser way.
  */
 window.requestAnimFrame = (function() {
   return window.requestAnimationFrame ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame ||
          window.oRequestAnimationFrame ||
          window.msRequestAnimationFrame ||
          function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
            window.setTimeout(callback, 1000/60);
          };
 })();

How would I declare this in my typescript file so I won't get compile errors when I use the function:

 function tick()
 {
      requestAnimFrame(tick);
      drawScene();
 }

I now have tried:

 interface window
 {
      requestAnimFrame(): any;
 }

But this doesn't remove the error:

 The name 'requestAnimFrame' does not exist in the current scope
like image 639
Toad Avatar asked Feb 05 '13 20:02

Toad


2 Answers

You were heading in the right direction, but you need to define all of the variations you have:

 interface Window {
     requestAnimFrame(callback: any, element?: any): void;
     webkitRequestAnimationFrame(callback: any, element?: any): void;
     mozRequestAnimationFrame(callback: any, element?: any): void;
     oRequestAnimationFrame(callback: any, element?: any): void;
 }

 window.requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback, element?) {
            window.setTimeout(callback, 1000/60);
        };
 })();

function tick() {
    window.requestAnimFrame(tick);
}
like image 115
Fenton Avatar answered Sep 23 '22 16:09

Fenton


make sure the interface name starts with capital "W" not "w"

interface Window {
   requestAnimFrame():any;
}

In the calling code use window.requestAnimFrame();. Hope this will solve your problem

like image 24
Rajeesh Avatar answered Sep 20 '22 16:09

Rajeesh