2016-10-22 77 views
2

我有一個JS對象:Knockout.js與映射對象綁定和訂閱屬性更改

var bookmark = { 
    id: 'id', 
    description: 'description', 
    notes: 'notes' 
} 

我要綁定到整個對象,在一個textarea顯示註釋,並且訂閱修改筆記。

這是我到目前爲止有:

this.bookmark = ko.observable(); 

this.bookmark.subscribe = function(bookmarkWithNewNotes) { 
    //use the bookmarkWithNewNotes.id to update the bookmark in the db 
} 

我設置書籤,像這樣:

this.bookmark(ko.mapping.fromJS(existingBookmark)); 

的看法是這樣的:

<div databind="with: $root.bookmark" > 
    Notes 
    <textarea class="userNotes" rows="10" data-bind="value: notes" ></textarea> 
    </div> 

這ISN」不工作。我需要做些什麼才能按照我希望的方式工作?

謝謝!

+0

請使用Stack Snippets('<>'工具欄按鈕)使用** runnable ** [mcve]更新您的問題,以便我們可以在上下文中輕鬆查看問題並幫助您解決問題。 –

+0

我只是試圖和我不能讓外部映射文件正常工作。很累。我會在早上再試一次。 – MayNotBe

+0

順便說一句,它的數據綁定=「」不databind =「」 – Joonas89

回答

0

以下是Fiddle中的示例。

你可以做這樣的事情:

<div> 
    Notes 
    <div data-bind="foreach: bookmarks"> 
     <textarea rows="10" data-bind="value: note"></textarea> 
    </div> 
</div> 

,併爲你的書籤創建視圖模型,就像這樣:

function BookmarkViewModel(id, description, note) { 
    var self = this; 

    self.id = id; 
    self.description = ko.observable(description); 
    self.note = ko.observable(note); 

    self.note.subscribe(function(val) { 
     alert("Save note, id: " + self.id + ", description: " + self.description() + ", note: " + self.note()); 
    }); 

    return self; 
} 

得到您的數據後,爲每個項目創建虛擬機,像這樣:

function AppViewModel(data) { 
    var self = this; 

    self.bookmarks = ko.observableArray(); 

    for (var i = 0; i < data.length; i++) { 
     self.bookmarks().push(new BookmarkViewModel(data[i].id, data[i].description, data[i].note)); 
    }; 

    return self; 
} 

可以CRE吃了一個單獨的服務來獲取你的數據,我只是嘲笑了這個poc。

$(function() { 

    var data = [{ 
     id: 1, 
     description: 'some description', 
     note: 'some note' 
    }, { 
     id: 2, 
     description: 'some other description', 
     note: 'some other note' 
    }]; 

    ko.applyBindings(new AppViewModel(data)); 
}); 
+1

謝謝。這讓我走上了正軌,並且我能夠實施一個工作解決方案。 – MayNotBe