2013-06-27 55 views
3

我們應該如何在打字稿中聲明viewmodels?打字稿中的Knockout Viewmodel

作爲類,模塊或var /函數?

在他們使用var和功能definitelytyped例子大多https://github.com/borisyankov/DefinitelyTyped/blob/master/knockout/tests/knockout-tests.ts

編輯:謝謝您Basarat - 在此編輯我延長了一個問題: 如果我使用類,我想這應該是這樣的:

class Player 
{ 
    min:KnockoutObservable<number>; 
    constructor(min:number=0) 
    { 
     this.min=ko.observable(min); 
    } 
} 

但如何定義計算?

回答

5

您可以使用計算與仿製藥(最新打字稿0.9),只是在聲明中定義類型和構造將分配值調用的結果ko.computed:

export class Inbox extends vm.BriskIdeaViewModel { 

    public rapidEntryText = ko.observable<string>(); 
    public todosActive: KnockoutComputed<Array<ITodo>>; 

    constructor() { 
     super(); 
     this.todosActive = ko.computed(() => { 
      return _.filter(this.dataContext.todos(), x => !x.isDone()); 
     }); 
    } 
} 
+0

爲什麼你使用public和爲什麼()在rapidEntryText = ko.observable ()? (我知道observables是函數,但VS強調它是一個錯誤) –

+0

公衆只是個人偏好 - 它是相同的,沒有公開(打字稿默認情況下是公共的,除非你把它設爲私人)。 – nihique

+0

and rapidEntryText = ko.observable ();是有默認值 - 你可以將這個assigment分離到構造函數(就像this.todosActive一樣),但是這更容易。 – nihique

3

我更喜歡使用類,因爲它們確實封裝了非常好的功能。

例如一個簡單的類:

class Player { 
    min = ko.observable(0); 
    sec = ko.observable(0); 
    mil = ko.observable(0); 
} 

,然後做一個簡單的應用:

var vm = new Player(); 
    ko.applyBindings(vm); 
+1

我一直在等待有人(除了我之外:P),以KO觀測與模型仿製藥 - 它們似乎爲它量身定做。你有嘗試過嗎? – JcFx

+0

@JFFx Nope。雖然我做了大量的通用工作:https://github.com/basarat/typescript-collections我非常喜歡AngularJS淘汰賽。我知道的所有淘汰賽現在已經一歲了:) AngularJS現在是我的第二天性了:) – basarat

+0

不要劫持你的答案,但希望能夠增加它的實用性,有人有:http://typescript.codeplex.com/discussions/441964 – JcFx