javascript Knockout:写入和读取计算属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10323503/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:28:08  来源:igfitidea点击:

Knockout: writing and reading a computed property

javascriptknockout.js

提问by Matteo Pagliazzi

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.

如果 title 有值,请使用它,但如果它是空白的,请使用内容中的前 20 个字符 + "..."。

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?

RP Niemeyer 回答中的唯一问题是我必须只拥有用于读/写的财产,这可能吗?

回答by RP Niemeyer

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

在创建可写的计算 observable 时,您将需要一个单独的 observable 来包含实际标题。

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