0

This demo is working fine, but when I change it to this demo nothing:

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

Matt Tester
  • 4,663
  • 4
  • 29
  • 32
Gildas.Tambo
  • 22,173
  • 7
  • 50
  • 78

1 Answers1

2

If you are insist to use an object literal as your view model you need set the deferEvaluation to true on your computed in order to access the viewModel inside the computed:

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

Demo JSFiddle.

Or declare your computed after you have created the viewModel object:

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

Demo JSFiddle.

Community
  • 1
  • 1
nemesv
  • 138,284
  • 16
  • 416
  • 359
  • somehow it doesn't work in durandal it is the same but with `return viewModel` point a breackpoint gives me `: undefined` – Gildas.Tambo Mar 25 '14 at 13:35
  • Then this is something which is durandal related, so you should post this issue as a separate question including your durandal viewModel. – nemesv Mar 25 '14 at 15:51
  • can you please check this now? http://stackoverflow.com/questions/22741620/what-am-i-doing-wrong-here-returing-viewmodel – Gildas.Tambo Mar 30 '14 at 08:16