2012-04-24 60 views
0

我刚开始的淘汰赛此模型和视图模型:KnockoutJS和计算性能不工作

$(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个charachters从内容+“...”

但这好好尝试工作...

有关这样做的任何建议,也以其他方式?

回答

4

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) + "..."; 
}); 

请注意,我搬到了观察到的“内容”顶端的创作,因为当创建一个计算的观察值,它的初始值被计算一次 - 所以我们可能需要可观察到的“内容”存在。

+0

它的工作除了2个问题,我已经更新了问题来解释它更好......现在感谢! – 2012-04-24 16:32:17

+0

这种行为非常自然 - 每当您编辑内容时,标题也会更新。你需要更多的技巧才能实现这一点。第二个问题:如果你想写一个计算的observable,你需要指定它应该如何在内部工作(参见http://knockoutjs.com/documentation/computedObservables.html)。我恢复了原来的问题(它可能会帮助其他人) - 如果您有更多问题,请打开一个新问题。 – Niko 2012-04-24 16:37:22

+0

阅读关于reand和写但仍然不工作:(但我已经在这里打开另一个问题http://stackoverflow.com/questions/10323503/knockout-writing-and-reading-a-computed-property – 2012-04-25 21:04:19