【发布时间】:2011-06-10 16:33:01
【问题描述】:
我正在尝试使用 KnockoutJS 构建一个交互式仪表板,其中包含style 属性的不同方面的数据绑定;即left、top、width和height。例如,我使用 JQuery UI 以及 ui-draggable 和 ui-resizable 效果来使用户能够在画布上拖动面板并调整它们的大小,但他们认为合适。如果没有 KnockoutJS,我只是在遍历每个 div 并从 dom 元素中窃取这些属性。我确信使用 KnockoutJS 有更好的方法,对吧?
为了更好地解释我的问题,请并排考虑两个面板:
<div id='dashboard'>
<div id='panel1' class='ui-draggable ui-resizable' data-bind='?????'>
<!-- content goes here -->
</div>
<div id='panel2' class='ui-draggable ui-resizable' data-bind='?????'>
<!-- content goes here -->
</div>
<button data-bind='click: send'>Update</button>
</div>
我的视图模型看起来像这样(注意:为简洁起见,伪编码):
var viewModel = {
panels: [
{ id: 'panel1', left: 0, top: 0, width: 50; height: 50 },
{ id: 'panel2', left: 50, top: 0, width: 50; height: 50 } ],
send: function() {
ko.utils.postJson( location.href , { panels: this.panels } );
}
};
ko.applyBindings( '#dashboard', viewModel );
我想以这样一种方式绑定它,当用户调整任何 div 元素(即面板)的大小时,它会使用内置数据绑定 OnMouseUp 更新底层 viewModel。然后,当用户单击“更新”按钮时,我会将坐标发布到服务器。
我认为这可能与自定义模板有关,但即便如此,我在管理每个面板上的鼠标事件时也遇到了一些我无法完全掌握的复杂性。
<script type='text/html' id='panelTemplate'>
<div class='ui-draggable ui-resizable'
style='top: ${ top }; left: ${ left }; width: ${ width }px; height: ${ height }px;'>
<!-- content goes here -->
</div>
</script>
想法?
【问题讨论】:
标签: javascript data-binding knockout.js