Search code examples
jquery-uibackbone.jsjquery-ui-draggablejquery-ui-droppable

Jquery Draggable and Backbone.js getting reference to backbone model from inside the droppable success callback


I've got a backbone view model that I'm rendering here and making it draggable with jquery ui.

render: ->
$(this.el).attr('class', 'item').html(this.template(this.options.model.toJSON() ))
viewmodel = this
$(this.el).draggable
    revert: true
    drag: () ->
        console.log(viewmodel)

Above, I have viewmodel available and can remove it from the dom, call methods on its model, etc. But what I want is to drag this view model into a droppable container --like a trash can-- and then call a few of the view model's methods and remove it from the DOM.

What I see though, is the callback method for when an item is dropped into a container would be:

$(function() {
    $("#trash").droppable({
        drop: function(event, ui) {
          console.log(ui.draggable);
        }
    });
});

So, I'm able to see ui.draggable and remove it from the DOM, but i have no reference to its view model. Am I doing something wrong? Any way to work around this?


Solution

  • I've had this problem. I solved it thusly: Give the drop target a reference to the model collection. Set a property data-cid="<%= cid %>" on the draggable. Now you can look up the model in the collection from the $(ui.draggable).data('cid'). Since backbone asserts that CIDs are unique, you could even scan a collection of collections, in case there were multiple model classes you wanted to be trashable.