Search code examples
javascriptclassdrag-and-dropmootoolsexpand

Mootools - add variables to all draggable and droppable elements with .implement



Im making a drag and drop system with mootools drag.move class, but i need all the draggable and droppable elements to have some extra variables and maybe add in a function or two. Ive researched on how to do this using .implement but Ive got no idea how to fit that into my code:

window.addEvent('domready', function(){

 $$('#draggables DIV').makeDraggable({

droppables: $$('#droppables DIV'),

onEnter: function(draggable, droppable){
    droppable.setStyle('background', 'orange');
    droppable.setStyle('opacity', '0.4');
    snap_left = droppable.getStyle('left');
    snap_top = droppable.getStyle('top');   
    document.getElementById("slot").innerHTML=droppable.id;
},

onLeave: function(draggable, droppable){
    droppable.setStyle('background', null);
},

onDrop: function(draggable, droppable){

    if (droppable){
        droppable.setStyle('background', '');
        draggable.setStyle('left', snap_left );
        draggable.setStyle('top', snap_top );                   
    } else {
        draggable.setStyle('left', snap_left );
        draggable.setStyle('top', snap_top );
    }
}

 });

});

Is what I want posible using .implement?
Can I add these things to all draggable and droppable elements?
ty in advance!

-Thaiscorpion

edit:
Ive tried adding options directly to the main class in the mootools library and tried accesing them from the onEnter event like this:

    onEnter: function(draggable, droppable){

if (droppable.occupied){ //here is where im tryin to acces it, the default option is set to occupied: true droppable.setStyle('background', 'red'); droppable.setStyle('opacity', '0.4'); document.getElementById("slot").innerHTML=droppable.id; } else { droppable.setStyle('background', 'orange'); droppable.setStyle('opacity', '0.4'); snap_left = droppable.getStyle('left'); snap_top = droppable.getStyle('top'); document.getElementById("slot").innerHTML=droppable.id; } },

but not getting anything to work.


Solution

  • you can use element storage.

    draggable.store("occupied", true);
    

    ....

    if (draggable.retrieve("occupied") === true) {
    
    }
    

    .... functions or anything can be stored per element

    element.store("somekey", function() {
        element.toggleClass("foo");
    });
    
    element.retrieve("somekey").call(element);
    

    and so forth.

    to use Implement:

    Element.implement({
        dragfoo: function() {
            this.set("drag", { });
            return this;
        }
    });
    
    // allows you:
    
    $("someid").dragfoo();
    

    though if you need storage, use storage and dont store properties on the actual element. mootools storage really uses an object hash table that's behind a closure. having proprietary element attributes/properties in IE can slow things down considerably in element access.