我在这里做错了计算?

时间:2014-03-25 12:43:01

标签: knockout.js

demo工作正常,但当我将其更改为此demo时:

ko.bindingHandlers.limitCharacters = {
    update: function(element, valueAccessor, allBindingsAccessor, viewModel)
    {
        var allowedNumberOfCharacters = valueAccessor();
        var currentValue = allBindingsAccessor.get('value');
        var cutText = ko.unwrap(currentValue).substr(0, allowedNumberOfCharacters);
        currentValue(cutText);
    }
};

var viewModel = {
    comment : ko.observable(""),
    count : ko.computed(function(){
        var countNum = 20 - viewModel.comment().length;
        return countNum;
    })
};
ko.applyBindings(viewModel);

DEMO not working

enter image description here

1 个答案:

答案 0 :(得分:2)

如果您坚持使用an object literal作为视图模型,则需要设置deferEvaluation to true on your computed以访问计算内的viewModel

var viewModel = {
    comment : ko.observable(""),
    count : ko.computed(function(){
        var countNum = 20 - viewModel.comment().length;
        return countNum;
    }, null,  { deferEvaluation: true })
};

演示JSFiddle

或者在创建viewModel对象后声明计算:

var viewModel = {
    comment: ko.observable(""),
};
viewModel.count = ko.computed(function () {
    var countNum = 20 - viewModel.comment().length;
    return countNum;
});

演示JSFiddle