2012-04-24 61 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