typescript 我可以在打字稿中覆盖 document.ready

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15391681/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:48:32  来源:igfitidea点击:

Can I override document.ready in typescript

jqueryonloadtypescriptdocument-readyonload-event

提问by Mavi Domates

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.

我有一个应用程序,它有不同的页面,大致每个页面都有自己的 js(由打字稿编译器生成)。每个页面的 document.ready 方法都有一些共享属性,我希望将共享函数/属性放入一个基本的打字稿类中。

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?

可以这样做吗?我不确定这是否可能?

回答by Bill Ticehurst

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:

您可以在包含公共行为和属性的 .ts 文件中拥有一个 PageBase 类,然后从该类派生出每个页面特定行为的类。类似于以下内容:

// 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...

上面 (base.js) 的编译输出将通过每个页面上的脚本标记包含在内,然后是由类似...

// 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?

这听起来与你所追求的有关吗?

回答by Nikos

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..

但是如果你在 .ts 文件的顶部声明一个函数 var 并从你的外部 doc.ready 东西中调用它,你可以听到该函数在类实例中的变化..

see

Function listener in javascript and/or jQuery

javascript 和/或 jQuery 中的函数侦听器

and Listen to state and function invocations

侦听状态和函数调用