淘汰赛:编写和读取计算属性 [英] Knockout: writing and reading a computed property
本文介绍了淘汰赛:编写和读取计算属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个具有两个属性的模型:标题和内容,我想做的是:
I have a model with two property: title and content and what I want to do is:
如果title具有值,请使用它,但如果其为空白,请使用内容的前20个字符+"...".
If title has a value, use it but in case it's blank use the first 20 chars + "..." from content.
这是模型:
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..
RP Niemeyer回答中的唯一问题是,我只能拥有用于读/写的属性,这可能吗?
推荐答案
在创建可写的可计算观察值时,您将需要一个单独的观察值来包含实际标题.
When creating your writeable computed observable, you will want to have a separate observable to contain the actual title.
更像是:
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
});
}
这篇关于淘汰赛:编写和读取计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文