Search code examples
javascriptjqueryjquery-uidraggablejquery-events

Pass arguments or containing object to jQuery UI draggable events


Say I have following code:

var mainObj = {
  area: $("#elementsArea"),
  elements: [],

  addElement: function (x, y) {
    var newElement = $('<div class="element"></div>');
    newElement.css("top", y);
    newElement.css("left", x);
    newElement.appendTo(this.area);
    this.elements.push( { id: this.elements.length, x: x, y: y } );
    newElement.dragabble({
      stop: function () {
        // What to do here?
      }
    });
  },

  updateElement: function ( element_id, x, y ) {
    // Find element in this.elements table table and update x, y
  },

  setup: function () {
    this.area.bind('click', this, function (e) {
      e.data.addElement( e.offsetX, e.offsetY );
    });
  }
}

$(document).ready( function () { mainObj.setup() } );

HTML, and CSS are irrelevant, other attributes and functions too. What I want to do is to somehow pass new position after draggable event stops to the updateElement method, so I can update object in elements table, similar to what I did with click event.

How can I do it, or did I make something bad with code design?


Solution

  • The stop function has two parameters, I think you can reach from them those information what you need for update, something like this:
    http://api.jqueryui.com/draggable/#event-stop

    newElement.dragabble({
        stop: function (event, ui) {
            var element_id = ui.helper.attr('id');// or get id as you want
            // ui.position or ui.offset try what you need
            this.updateElement(element_id, ui.position.top, ui.position.left);
        }
    });
    

    (haven't tested just an idea schema)

    tested and improved version:

    addElement: function (x, y) {
        var self = this;// self is an alias for this
        var id = 'id_' + this.elements.length;// create unique ID
        var newElement = $('<div class="element"></div>');
        newElement.css("top", y);
        newElement.css("left", x);
        newElement.attr('id', id);//add ID for element
        newElement.appendTo(this.area);
        this.elements.push( { id: id, x: x, y: y } );
        newElement.dragabble({
           stop: function () {
              var element_id = ui.helper.attr('id');
              // ui.position or ui.offset try what you need
              self.updateElement(element_id, ui.position.top, ui.position.left);
            }
        });
    },