[英]How to efficiently toggle classes with multiple HTML elements across multiple files
[英]Mixing TypeScript and Meteor - Classes across multiple files
對任何不正確的術語表示歉意。 對於那些不熟悉Meteor的人來說, 它有一個明確定義的腳本加載順序 。 我正在嘗試創建包含類的許多*.ts
文件,就像你在C#的*.cs
文件中看到的那樣。 我想在彼此之間引用這些*.ts
文件,最終從main.ts
。
編譯Car.ts:
class Car {
constructor(public age: number) { }
}
生成Car.js:
var Car = (function () {
function Car(age) {
this.age = age;
}
return Car;
})();
使用Meteor,我想要以下輸出:
Car = (function () {
function Car(age) {
this.age = age;
}
return Car;
})();
因此可以從另一個文件main.ts引用Car:
/// <reference path="car.ts"/>
Meteor.startup(function () {
console.log(Car); // Hopefully prints [Function: Car]
var a: Car = null; // Compiles
});
我可以通過修改Car.ts來接近:
declare var Car;
class Car_ {
constructor(public age: number) {}
}
Car = Car_;
但是這產生了一個kludgy輸出:
var Car_ = (function () {
function Car_(age) {
this.age = age;
}
return Car_;
})();
Car = Car_;
並且需要一個kludgy main.ts:
/// <reference path="car.ts"/>
Meteor.startup(function () {
console.log(Car); // Prints [Function: Car_]
var a: Car_ = new Car(); // Yuck!
});
有什么建議? 我可能會像C#應用程序那樣對待它。
一種解決方案涉及設置全局對象:
class Car {
constructor(public age: number) {}
}
global.Car = Car;
編譯為:
var Car = (function () {
function Car(age) {
this.age = age;
}
return Car;
})();
global.Car = Car;
我對這個解決方案不是很滿意,因為global
是一個特定於nodejs的東西,並且不能在使用window
的瀏覽器中工作。 事實證明this
在瀏覽器和服務器上都有效:
class Car {
constructor(public age: number) {}
}
this.Car = Car;
編譯為:
var Car = (function () {
function Car(age) {
this.age = age;
}
return Car;
})();
this.Car = Car;
不雅,但更好......
我昨天遇到了同樣的問題。 我正在使用meteortypescript ,它給了我同樣的問題(似乎它不允許與包正常工作)。
我切換到另一個編譯器腳本,現在一切正常。 這是: mologie:typescript ,.
我沒有看到解決第一個問題的方法,但我偶然發現了兩個編譯器插件的作者之間的討論,這可能解釋了一些差異: https : //github.com/mologie/meteor-typescript /問題/ 1
可能會有所幫助
我在我的博客和這里處理過這個問題。 我決定使用邪惡的eval
命令,因為它給了我最簡單的使用模塊的可能性,直到出現更復雜的東西。
文件/lib/foo.ts
。 它位於子目錄中,因為它必須在Bar之前加載,因為它擴展了Foo。
eval('var Hugo = (this.Hugo || (this.Hugo = {})'); // this will override the automatically emitted var Hugo and assigns it with globally defined Hugo module
module Hugo {
export class Foo {
foo():string {
return 'foo'
}
}
}
文件/bar.ts
/// <reference path="lib/foo.ts"/>
eval('var Hugo = (this.Hugo || (this.Hugo = {})'); // this will override the automatically emitted var Hugo and assigns it with globally defined Hugo module
module Hugo {
export class Bar extends Foo {
bar () : string {
return 'bar';
}
}
}
文件/test.ts
/// <reference path="lib/foo.ts"/>
/// <reference path="bar.ts"/>
var m = new Hugo.Bar();
console.log(m.bar());
console.log(m.foo());
如前所述,對於類,解決方案甚至更簡單:
class ExportedClass {
variable : int;
}
this.ExportedClass = ExportedClass;
廢料TS和Meteor只會運行.js文件。
我可能會像C#應用程序那樣對待它。
是。 從var Car
刪除var
在這種特殊情況下沒有變化(兩者都是全局的)。
以下工作正常。 只需將car.ts
移動到子文件夾中:
/// <reference path="./foo/car.ts"/>
Meteor.startup(function () {
console.log(Car); // Hopefully prints [Function: Car]
var a: Car = null; // Compiles
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.