敲除attr绑定

时间:2016-04-22 21:48:46

标签: javascript knockout.js binding

我正在尝试从计算的observable中添加一个类,但我一直收到一个未定义的错误。我在这里做错了什么?

这是数据绑定:

<div data-bind="if:lcmsViewModel.lcms_instruments().hasOwnProperty('INSTR103')">
<instrument class="offset-2" data-bind="attr: { class: lcmsViewModel.lcms_instruments().INSTR103.color_class }">77</instrument>
</div>

以下是模型:

var InstrumentModel = function() {
    this.batch_id             = ko.observable()
    this.completion_time      = ko.observable()
    this.completed            = ko.observable()
    this.position             = ko.observable()

    this.time_left = ko.pureComputed(function(){
        var then = moment(this.completion_time()).utc().format("X")
        var now  = moment().local().format("X")

        var time_remaining = then - now;
        var hours = Math.floor((time_remaining/60)/60);
        return hours;
    }, this)

    this.time_class = ko.pureComputed(function(){
        if(this.time_left() > 6) {
            return 'lightgreen'
        } else if (this.time_left() < 6 && this.time_left() > 4) {
            return 'green'
        } else if (this.time_left() < 4 && this.time_left() > 0) {
            return 'darkgreen'
        } else {
            return 'blank'
        }
    }, this)
}

如果我这样做,我得到了正确的结果,并且没有未定义:

lcmsViewModel.lcms_instruments().INSTR1.time_class()

但是当页面加载时我收到以下错误:

knockout-3.2.0.js:63 Uncaught TypeError: Unable to process binding "attr: function (){return { class:lcmsViewModel.lcms_instruments().INSTR1.time_class} }"
Message: Cannot read property 'time_class' of undefined

0 个答案:

没有答案
相关问题