Matteo Pagliazzi
Matteo Pagliazzi

Reputation: 5260

Knockout: writing and reading a computed property

I have a model with two property: title and content and what I want to do is:

If title has a value, use it but in case it's blank use the first 20 chars + "..." from content.

This is the model:

       function Note(title, content) {
        var self = this;

        self.content = ko.observable(content);
        self.title = ko.computed({
          read: function(){
            if(!title){
              var content = self.content();
              if(content) return content.substring(0,19) + "...";
            }
          },
          write: function(title){
           return title;
          }
        });
       }

Title value gets correctly updated from content but it's impossible (for me) to get writing directly on title working..

The only problem in RP Niemeyer answer is that i must have only on property for reading/writing, is that possible?

Upvotes: 3

Views: 15666

Answers (1)

RP Niemeyer
RP Niemeyer

Reputation: 114792

When creating your writeable computed observable, you will want to have a separate observable to contain the actual title.

More like:

function Note(title, content) {
    var self = this;

    self.content = ko.observable(content);
    self.title = ko.observable(title);

    self.displayTitle = ko.computed({
        read: function() {
            var title = self.title();
            if (!title) {
                var content = self.content();
                if (content) return content.substring(0, 19) + "...";
            }

            return title;
        },
        write: self.title
    });
}​

Upvotes: 11

Related Questions