2

我正在尝试将以下代码转换为咖啡脚本作为一种练习

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);
});

现在我在coffeescript中有这段代码,但我遇到了自引用@编译到错误范围的问题:

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)

有这样做的规范方法吗?

4

1 回答 1

2

好的......我做了一些搜索后让它工作:

https://groups.google.com/forum/?fromgroups=#!topic/knockoutjs/CTBLQthLGWU

我没有做两件事......一是我没有@在构造函数声明中添加,另一件事是使用=>而不是->

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)
于 2012-09-20T21:34:04.407 回答