Can I override document.ready in typescript

Mavi Domates picture Mavi Domates · Mar 13, 2013 · Viewed 16.3k times · Source

I have an application which has different pages and roughly every page has it's own js (which are generated by typescript compiler). document.ready method for every page has some shared attributes and I'm looking to put the shared functions / properties into a base typescript class.

So it should look like

 class PageX extends BasePage
    {
        onLoad => which should act like document.ready
    }

can this be done? I'm not sure if it's possible?

Answer

Bill Ticehurst picture Bill Ticehurst · Mar 14, 2013

If you want the base functionality in every page, then you'd need to include the base script in every page. Deriving a class does not copy the parent functionality into the child.

You could have a PageBase class in a .ts file that contains the common behavior and properties, and then derive from this a class for each page specific behavior. Something like the below:

// Base.ts
class PageBase {
  commonProperty: any;

  constructor(doc:HTMLDocument){
    doc.onload = function(){
      alert('Common code here');
    }
  }
}

The compiled output from the above (base.js) would be included via a script tag on every page, followed by the script per page generated by something like...

// pageX.ts

/// <reference path="Base.ts"/>
class PageX extends PageBase {
  constructor(){
    super(window.document);
    // Rest of my code here...
  }
}

Does this sound about what you were after?