Search code examples
htmldrag-and-dropknockout.jsjquery-templates

How to use HTML5 drag and drop in combination with KnockoutJS?


I can't seem to bind to html5 drag and drop events.

Here's an example of from a template:

<script id="tabsTemplate" type="text/html">
    <div class="dropzone" for="tab"
        data-bind="event:{dragover: function(event){event.preventDefault();},
                          dragenter: function(event){event.target.addClass('dragover'); event.preventDefault();},
                          dragleave: function(event){event.target.removeClass('dragover'); event.preventDefault();}}
                          drop: function(event){console.log('blahblah!')}"></div>
    <h1 class="tab" draggable="true"
      data-bind="attr: {selected: $data.name === $item.selected()},
                 click: function(){$item.selected($data.name)},
                 event:{ dragstart: function(event){console.log('blah!!')},
                         dragend: function(event){document.getElementsByClassName('dragover')[0].removeClass('dragover')}}">
        ${name}

        <img src="icons/close-black.png" class="close button" role="button"
            data-bind="click: function(e){$item.close($data)}">
    </h1>
</script>

What I have should work as expected... and it does as long as I make them normal inline ones. However, then the other bindings don't work!

I am getting this error message:

Uncaught SyntaxError: Unexpected token '||' jquery-tmpl.js:10

What's going on here? Is there something I'm doing wrong?


Solution

  • OK, I have worked it out. It seems I missed in the documentation where it said that in knockout, by default it makes all events prevent default / return false. So all I had to do was make my dragstart handler return true, and now it works. Phew!!