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

jdkealy picture jdkealy · Sep 7, 2011 · Viewed 11.1k times · Source

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?

Answer

Christopher Scott picture Christopher Scott · Oct 12, 2011

I think I ran into the same issue; instead of adding meta-data to the element or storing it globally, I just stored a reference to the actual view itself on the DOM element, which then gives you access to the model, and any info you need from there.

window.MyDraggableView = Backbone.View.extend({
    initialize: function(){
        $(this.el).draggable();
        $(this.el).data("backbone-view", this);
    }
});

window.MyDropTarget = Backbone.View.extend({
    initialize: function(){
        $(this.el).droppable({
            drop: function(ev, ui){
                // get reference to dropped view's model
                var model = $(ui.draggable).data("backbone-view").model;
            },
        });
    },
});