b3.
b3.

Reputation: 7155

Is it possible to use multiple callbacks in the WindowButtonMotionFcn?

I created a class which adds functionality to a figure on construction. This class creates a listener for the WindowMouseMotion event; however, to get this event to fire I had to add a dummy callback function for the figure's WindowButtonMotionFcn property. I first check if this property is already populated. If it isn't then I set it to a dummy callback function that does nothing.

Instead of checking if the property is already set or not, can I simply add this dummy callback to any existing callbacks? Is it possible for a callback property to call multiple functions?

EDIT

When using the handle.listener approach to handle the WindowButtonMotionEvent event given below, be sure to use eventdata.CurrentPoint to access the current mouse position. The CurrentPoint property of the figure does not get updated before handling the WindowButtonMotionEvent event in this manner.

Upvotes: 4

Views: 2679

Answers (2)

janh
janh

Reputation: 2096

You can do this via cellfun and feval, as answered on Mathworks site: http://www.mathworks.com/matlabcentral/answers/10664-multiple-callback-functions

obj = uicontrol(...,'style','popupmenu',...
  'Callback', @(h,e)(cellfun(@(x)feval(x,h,e), ...
   {@(h,e)this.myfunc(h), ...
   @(h,e)this.myfunc2(h), ...
   @(h,e)this.myfunc2(h)}))

Note that the callback is set to an anonymous function using cellfun to evaluate each handler.

Upvotes: 0

gnovice
gnovice

Reputation: 125854

A related article can be found on Yair Altman's Undocumented MATLAB blog, from guest blogger Matt Whitaker. What you are alluding to is callback chaining, and quoting from the blog:

Frankly, having written code previously that handles callback chaining, I would rather poke myself in the eye with a fork!

Luckily, there appears to be an alternative solution in that article. Using a snippet from the code posted there, I was able to get a function to execute on mouse movement without having to set the 'WindowButtonMotionFcn'. I added a listener to the current figure like so:

myListener = handle.listener(gcf,'WindowButtonMotionEvent',...
                             @(hSource,eventData) disp('hello'));

And the message hello was displayed when I moved the mouse in the window.

Upvotes: 3

Related Questions