Question

Help me please, how call method inside callback?

Example:

var methods = {
     init : function( settings ) { 
     },
     destroy : function( ) {  },
     reposition : function( ) { },
     show : function( ) { },
     hide : function( ) { },
     myfunc : function() {}
  };

//
$.fn.myPlugin.defaults = {
        // CALLBACK
        onClickElement : function(element) {}
    };


$('#elementLi').myPlugin({
        onClickElement: function(element) { 
            // here call method myfunc
        }
});

How can call myfunc inside onClickElement?

Thank You! P.S. Sorry for my bad English

Was it helpful?

Solution

By convention event handlers should set this to be the element that's associated with the event.

Your plugin should also arrange to pass the original event to whatever function has been configured in onClickElement, although you've not included that code here.

Putting that together, you ought to end up with:

$('#elementLi').myPlugin({
    onClickElement: function(event) {   // NB: *not* element
        methods.myfunc.call(this, event);
    }
});

alternatively, if you've followed the above advice you don't even need the additional function block:

$('#elementLi').myPlugin({
    onClickElement: methods.myfunc
});

So long as your callback uses .call(element, func) to invoke onClickElement it'll correctly set this to be the element and not methods.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top