Search code examples
javascriptmootools

Mootools onClick send object


I m trying to send an object to another out of the object it self.

var Tile = new Class({
    initialize : function(){
        this.inner = new Element(...);
        this.inner.addEvent('click', function() {
            popup.open(this);
        });
    }
});

If I m alerting any membervariable from Tile out op Popup it's alerting 'undefined'. What am I doing wrong?

var Popup = new Class({
    initialize : function(){
    },
    open : function(tile) {
        alert(tile.width);
    }
});

Kind regards!


Solution

  • When you pass this to the popup object, you are passing the element itself (which I believe is your intention). However, elements don't by default have a property called width.

    Perhaps you are looking for getSize();? This returns a two-property object (x and y), corresponding respectively to the width and height of the element.

    I've approximated your code into the following jsFiddle, give it a try: http://jsfiddle.net/g4SmJ/

    For reference, here is the new Popup class code:

    var Popup = new Class({
        initialize : function(){
        },
        open : function(tile) {
            size = tile.getSize();
            console.log(size);    // console.log provides a nicer interface for debugging, you can pass objects into it! Use the Chrome Inspector or Firebug to see its output.
            alert(size.x);
        }
    });
    

    In response to your comment:

    Oh ups I did not meant to alert the doms width, sorry for that. What I posted is smaller code from the full object. Width actually was a defined member in Tiles that I wanted to alert out of Popup

    In this case, then when you are sending the call to .open();, you passed this into the function call, but you are not passing the Tile object! Instead, you passed the inner element you created.

    Rewrite Tile thusly:

    var Tile = new Class({
        initialize : function(){
            var self = this;
            this.inner = new Element(...);
            this.inner.addEvent('click', function() {
                popup.open(self);
            });
        }
    });