[英]KnockoutJS and computed property not working
我刚开始敲除这个Model和viewmodel:
$(function() {
// Class to represent a note
function Note(title, content) {
var self = this;
self.title = ko.computed(function() {
var title = title;
if(title.length > 0) return title;
if(self.content && self.content.length > 0) return self.content.substring(0,19) + "...";
});
self.content = ko.observable(content);
}
// Overall viewmodel for this screen, along with initial state
function TaccuinoViewModel() {
var self = this;
// Editable data
self.notes = ko.observableArray([
]);
// Operations
self.addNote = function() {
self.notes.push(new Note());
}
self.removeNote = function(note) { self.notes.remove(note) }
}
ko.applyBindings(new TaccuinoViewModel());
});
问题在于计算属性:我想做的是:
1-)如果标题的长度> 0,请使用它2-)如果未定义标题,请使用内容+“ ...”中的前20个字符
但这不起作用...
是否有其他建议这样做?
self.content
是可观察的,因此您需要调用它以获取当前值:
self.content = ko.observable(content);
self.title = ko.computed(function() {
if(title.length > 0) return title;
var currentContent = self.content(); // <-- get the current value
if(currentContent) return currentContent.substring(0,19) + "...";
});
请注意,我已将可观察的“内容”的创建移至顶部,因为在创建计算的可观察的对象时,其初始值仅被计算一次-因此我们可能需要显示“内容”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.