我正在使用 Knockout.js 填充一组 HTML5<details>
元素。这是结构:
<div class="items" data-bind="foreach: Playlists">
<details class="playlist-details" data-bind="attr: {id: 'playlist-details-' + $index()}">
<summary>
<span data-bind="text: name"></span> - <span data-bind="text: count"></span> item(s)
<div class="pull-right">
<button data-bind="click: $parent.play, css: {disabled: count() == 0}, attr: {title: playbtn_title}" class="btn"><i class="icon-play"></i> Play</button>
<button data-bind="click: $parent.deleteList" class="btn btn-danger"><i class="icon-trash"></i> Delete</button>
</div>
</summary>
<div class="list" data-bind="with: items" style="padding-top: 2px;">
...
</div>
</details>
</div>
ViewModel 中的数据如下所示:
var VM = {
Playlists: [
{
name: "My Playlist1",
count: 3,
items: [<LIST OF SONG ID'S>],
playbtn_title: "Play this playlist"
},
{
name: "My Playlist2",
count: 5,
items: [<LIST OF SONG ID'S>],
playbtn_title: "Play this playlist"
},
{
name: "My Playlist3",
count: 0,
items: [],
playbtn_title: "You need to add items to this list before you can play it!"
}
]
};
我想添加记住详细信息视图的打开或关闭状态的功能。我之前使用jQuery
and localStorage
1实现了这种行为,但是对于这个项目,我想本地使用 Knockout 而不是使用 jQuery。
我在 ViewModel 中的播放列表中添加了一个属性,该属性是在页面加载时isOpen
检索的。localStorage
但是,我似乎不能attr
在 Knockout 中使用绑定,因为HTML5 规范说只查找属性的存在或不存在,open
而不是值。
当 ViewModel 的属性发生变化时,如何让 Knockout 添加和删除元素的open
属性?<details>
isOpen
1:像这样:
// On the initial page load.
contents += '<details ' + ((localStorage['tl_open_playlist-details-' + counter] == 1) ? 'open' : '') ' class="playlist-details" id="playlist-details-' + counter + '" data-name="' + escape(listname) + '">'
...
// Update storage when things are clicked.
$(document).on('DOMSubtreeModified', 'details.playlist-details', function() {
if ($(this).prop('open')) {
localStorage['tl_open_' + this.id] = 1;
} else {
delete localStorage['tl_open_' + this.id];
}
});