Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout js - Getting string length of observable

This seems to be a simple issue but I can't seem to figure it out

I just need to display the length of a string that is observable. I have tried achieving the result with a ko.computed() function as you can see in the code below, but it always returns zero.

Fiddle 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'));
like image 824
bzlies Avatar asked Aug 20 '14 19:08

bzlies


1 Answers

Your computed version is almost correct. Change it by this

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

DEMO

like image 183
Claudio Redi Avatar answered Oct 03 '22 01:10

Claudio Redi