计时器到达00:00时如何锁定

时间:2014-05-07 15:58:23

标签: javascript knockout.js

我目前有一组可以选择和保存的卡片。我也有一个计时器。我想要的是,当计时器到达00:00时,无法再选择或保存卡片。 这是我到目前为止所做的,最后我附上了一个小提琴。提前谢谢!

HTML

<div style="clear:both; height: 150px;">
    <div data-bind="foreach: items">
        <div class="profile" data-bind="text: name, click: $parent.clicked, enable: active, css: {highlight: active()}"></div>
    </div>
</div>
<hr>
<div id="timer">2:00</div>
<h2>Selected Card</h2>
<div data-bind="foreach: selectedItems">
    <div data-bind="text: name"></div>
</div>
<input type="button" data-bind="click: save" value="Save"></input>

CSS

.profile {
width: 50px;
height: 80px;
color: black;
background-image: url(http://images1.pixlis.com/background-image-checkers-chequered- checkered-squares-seamless-tileable-very-light-grey-saltpan-236nwb.png );
border: 1px solid black;
float: left;
line-height:80px;
text-align: center;    
margin: 2px;
}
.highlight {
background: yellow !important;
border:1px solid #000;
color: black;
}

使用Javascript /敲除

function Step(number) {
this.active = ko.observable(false);
this.name = ko.observable( number);
}

var model = function () {
var steps = [1,2,3,5,8,13,20,40,100];
for ( var i = 0 ; i < steps.length ; i++ )
steps[i] = new Step( steps[i] );
var items = ko.observableArray( steps )
var selectedItems = ko.computed(function () {
    return _.filter(items(), function (item) {
        return item.active();
    });
})

var clicked = function (item) {
    items().forEach(function(item){ item.active(false) });           
    item.active(!this.active());
};

var save = function () {
    alert("sending items \n" + ko.toJSON(selectedItems()));
}

return {
    items: items,
    selectedItems: selectedItems,
    save: save,
    clicked: clicked
}
}

function countdown(minutes) {
var seconds = 60;
var mins = minutes
function tick() {
    var counter = document.getElementById("timer");
    var current_minutes = mins-1
    seconds--;
    counter.innerHTML = 
 current_minutes.toString() + ":" + (seconds < 10 ? "0" : "") + String(seconds);
    if( seconds > 0 ) {
        setTimeout(tick, 1000);
    } else {

        if(mins > 1){  
           setTimeout(function () { countdown(mins - 1); }, 1000);

        }
    }
    }
    tick();
    }

countdown(2);

ko.applyBindings(model);

这是fiddle

1 个答案:

答案 0 :(得分:0)

如何实现这一目标有多种可能性,您可以通过界面创建方法,当达到时间时您将调用该方法。在模型内部,您还可以创建observable,它将被设置为锁定状态。

 var lock = function() {
        disableUIChanges(true);
    }

    var disableUIChanges = ko.observable(false);

参见小提琴上的例子 http://jsfiddle.net/gn4A4/4/

我建议您也遵循http://knockoutjs.com/文档中的建议。您可以像这样创建基类

var MyGame = function() {
   var self = this;
   self.steps = [1,2,3,5,8,13,20,40,100];
   ...
}

然后从游戏

创建myGame类和applyBindings的实例
var game = new MyGame();
ko.applyBindings(game);