I’m trying to use KnockoutJS to build an interactive dashboard with data bindings on different aspects of the style property; namely left, top, width, and height. For example, I’m using JQuery UI along with ui-draggable and ui-resizable effects to enable users to drag panels around on a canvas and resize them however they see fit. Without KnockoutJS, I was simply iterating over each div and stealing these properties from the dom element. I’m sure there’s a better way using KnockoutJS, right?
To explain my problem a little better, consider two panels side by side:
<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>
My view model looks something like this (note: pseudo coded for brevity):
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 );
I’d like to bind it in such a way that when the user sizes any of the div elements (ie. the panels), that it would then update the underlying viewModel using the built in data binding OnMouseUp. Then when the user clicks the “Update” button, I would then post the coordinates to the server.
I’m thinking it might have something to do with custom templates, but even there I ran into some complexities that I couldn’t quite grasp in managing the mouse events on each panel.
<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>
Ideas?
I was having exactly the same problem: bind a KnockoutJS model to collection of draggable and resizable divs. The solution is to use custom binding and handle the event of end of resize and end of drag, as I explain here.