Can I override document.ready in typescript

16,707

Solution 1

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?

Solution 2

I think that logic does not belong in a class.

but if you Declare a function var at the top of the .ts file and call that from your external doc.ready thing, you could listen to that function changing in the class instance..

see

Function listener in javascript and/or jQuery

and Listen to state and function invocations

Share:
16,707

Related videos on Youtube

Mavi Domates
Author by

Mavi Domates

Updated on June 21, 2022

Comments

  • Mavi Domates
    Mavi Domates almost 2 years

    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?

  • Mavi Domates
    Mavi Domates about 11 years
    Yes, this sounds about right. A better approach I've come across is to call $(document).ready(this.customMethod); in constructor which allows you to customize customMethod code in inherited classes.
  • Timothy Groote
    Timothy Groote over 8 years
    In case of a class that acts as a view controller, that logic might very well belong there.