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);
答案 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。