[英]Knockout.js binding with a mapped object and subscribing to property changes
I have a JS object: 我有一个JS对象:
var bookmark = {
id: 'id',
description: 'description',
notes: 'notes'
}
I want to bind to the entire object, display notes in a textarea, and subscribe to changes to notes. 我想绑定到整个对象,在文本区域中显示注释,并订阅对注释的更改。
Here's what I have so far: 这是我到目前为止的内容:
this.bookmark = ko.observable();
this.bookmark.subscribe = function(bookmarkWithNewNotes) {
//use the bookmarkWithNewNotes.id to update the bookmark in the db
}
I'm setting the bookmark like so: 我像这样设置书签:
this.bookmark(ko.mapping.fromJS(existingBookmark));
The view looks like this: 该视图如下所示:
<div databind="with: $root.bookmark" >
Notes
<textarea class="userNotes" rows="10" data-bind="value: notes" ></textarea>
</div>
This isn't working. 这不起作用。 What do I need to do to make this work the way I want it to work?
我需要做些什么才能使它按我希望的方式工作?
Thanks! 谢谢!
Here is a example in Fiddle . 这是Fiddle中的示例。
You could do something like this: 您可以执行以下操作:
<div>
Notes
<div data-bind="foreach: bookmarks">
<textarea rows="10" data-bind="value: note"></textarea>
</div>
</div>
and create viewmodel for your bookmark, like so: 并为您的书签创建viewmodel,如下所示:
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;
}
after you get your data, create VM for every item, like so: 获取数据后,为每个项目创建VM,如下所示:
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;
}
You can create a seperate service to get your data, i just mocked this for poc. 您可以创建一个单独的服务来获取您的数据,我只是为了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));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.