I have just started with knockout this Model and 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());
});
The problem is with the computed property: what i want to do is:
1-)if title has a length > 0 use it
2-)in case it’s not defined use the first 20 charachters from content + “…”
but this doens’t work…
any suggestion about doing this, also in other ways?
self.contentis an observable, so you need to invoke it in order to get the current value:Note that I’ve moved the creation of the observable “content” to the top, because when creating a computed observable, its initial value gets computed once – so we may need the “content” observable to be present.