Search code examples
javascriptdom-events

Use magic e in extend function


I have a basic Drop event handler like the following:

function Drop(e){
    e.preventDefault();
    var data=e.dataTransfer.getData("Text");
    var child = $('[target_id="'+data+'"]').get(0);
    e.target.appendChild(child);
}
function DropHandler(){}
DropHandler.prototype={
        ...
    Drop : Drop
}

Create a new object and extend the basic drop handler:

function AdminDropHandler(){}
//Extend the DropHandler
extend(AdminDropHandler,DropHandler);
//Override Drop method in AdminDropHandler
AdminDropHandler.prototype.Drop=function(){
    DropHandler.prototype.Drop.apply(this,arguments);
    var parent_id = e.target.id;// not defined error
    ...
}

It can extend the function of DropHandler but the e that I use seems lose. How to solve this problem?


Solution

  • You haven't defined e in the function anywhere. Try defining it:

    AdminDropHandler.prototype.Drop = function(e) {
        DropHandler.prototype.Drop.apply(this, arguments);
        var parent_id = e.target.id; // should work now
    };
    

    You can also do this, though it's not recommended because a formal parameter does the job just fine:

    AdminDropHandler.prototype.Drop = function() {
        var e = arguments[0];
        DropHandler.prototype.Drop.apply(this, arguments);
        var parent_id = e.target.id; // should work now
    };