Reputation: 1131
How are we supposed to declare viewmodels in typescript?
As classes, modules or as var/functions?
In the definitelytyped examples they use var and function mostly https://github.com/borisyankov/DefinitelyTyped/blob/master/knockout/tests/knockout-tests.ts
EDIT: Thank you Basarat - in this edit I extend the question: If I use class I suppose it should be like this:
class Player
{
min:KnockoutObservable<number>;
constructor(min:number=0)
{
this.min=ko.observable(min);
}
}
BUT how should computed be defined?
Upvotes: 4
Views: 6131
Reputation: 5788
You can use computed with generics (latest Typescript 0.9), just define type in declaration and in constructor you will assign value to result of call to 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());
});
}
}
Upvotes: 6
Reputation: 275857
I prefer to use classes since they really encapsulate functionality extremely well.
e.g. a simple class :
class Player {
min = ko.observable(0);
sec = ko.observable(0);
mil = ko.observable(0);
}
And then do a simple apply:
var vm = new Player();
ko.applyBindings(vm);
Upvotes: 3