Reputation: 14258
I'm trying to translate the following code to coffeescript as a practice
function StateVM() {
var self = this;
self.state = ko.observable("stopped");
self.counter = ko.observable(0);
self.timeStopped = ko.observable(new Date());
self.timeStarted = ko.observable(new Date());
self.currentTime = ko.observable(new Date());
self.timeRunning = ko.computed(function(){
var num = (self.currentTime() - self.timeStarted())/1000 >> 0;
return (num < 0) ? 0 : num;
});
self.isStopped = ko.computed(function(){
return (self.state() === "stopped");
});
self.isStarted = ko.computed(function(){
return (self.state() === "running");
});
$(document).ready(function(){
var vm = new StateVM();
ko.applyBindings(vm);
});
now I have this code in coffeescript but I am running into problems with the self referentials @
compiles into the wrong scope:
obs = ko.observable
cmp = ko.computed
class StateVM
constructor: ->
state = obs "stopped"
counter = obs 0
timeStopped = obs new Date
timeStarted = obs new Date
currentTime = obs new Date
timeRunning = cmp ->
x = (@currentTime() - @timeStarted())/1000 >> 0
x < 0 ? 0 : x
isStopped = cmp -> @state() == "stopped"
isStarted = cmp -> @state() == "running"
$ -> ko.applyBindings(new StateVM)
Is there a canonical way of doing this?
Upvotes: 2
Views: 505
Reputation: 14258
Okay... I got it working after doing some searching:
https://groups.google.com/forum/?fromgroups=#!topic/knockoutjs/CTBLQthLGWU
I didn't do two things... one was i didn't add the @
in the constructor declarations and another was to use the =>
instead of ->
obs = ko.observable
cmp = ko.computed
class StateVM
constructor: ->
@state = obs "stopped"
@counter = obs 0
@timeStopped = obs new Date
@timeStarted = obs new Date
@currentTime = obs new Date
@timeRunning = cmp =>
x = (@currentTime() - @timeStarted())/1000 >> 0
x < 0 ? 0 : x
@isStopped = cmp => @state() == "stopped"
@isStarted = cmp => @state() == "running"
@start = (->) ;
@stop = (->) ;
$ -> ko.applyBindings(new StateVM)
Upvotes: 2