Js Knockout - Getting Observable String Length

This seems to be a simple problem, but I cannot understand it.

I just need to display the length of the observed string. I tried to achieve the result using the ko.computed() function, as you can see in the code below, but it always returns zero.

Script with an example

Html

 <div id="vm"> <h2>The title is: <span data-bind="text: title"></span></h2> <h2>The length is: <span data-bind="text: title.length"></span></h2> <h2>Length from computed: <span data-bind="text: titleLength"></span></h2> <input data-bind="value: title, valueUpdate: 'keyup'"/> </div> 

Javascript

 function VM() { var self = this; self.title = ko.observable(); self.titleLength = ko.computed(function() { return self.title.length; }); } ko.applyBindings(VM(), document.getElementById('vm')); 
+6
source share
1 answer

Your calculated version is almost correct. Change it to

 return self.title().length; // <-- Notice () after title 

Demo

+5
source

Source: https://habr.com/ru/post/974122/


All Articles