3

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
  • 4,262
  • 2
  • 26
  • 45
  • Have you tried it to see what happens? – Vivin Paliath Mar 13 '13 at 17:00
  • I'm not sure how to do it. TypeScript generates the code below for just defining the page class var Page = (function () { function Page() { } return Page; })(); so what I'm looking for is without writing the document.ready on every page - a method of this class should be invoked when it finishes to load and playing with DOM. – Mavi Domates Mar 13 '13 at 17:10

2 Answers2

4

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?

Bill Ticehurst
  • 1,728
  • 12
  • 14
  • 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. – Mavi Domates Mar 25 '13 at 16:02
1

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

Community
  • 1
  • 1
Nikos
  • 7,295
  • 7
  • 52
  • 88