Knockout: writing and reading a computed property

风流意气都作罢 提交于 2020-01-24 12:56:47

问题


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?


回答1:


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
    });
}​


来源:https://stackoverflow.com/questions/10323503/knockout-writing-and-reading-a-computed-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!