What does the string in 'DeleteFcn' evaluate to?

4 vues (au cours des 30 derniers jours)
Amit Singh
Amit Singh le 6 Juin 2018
Modifié(e) : Stephen23 le 6 Juin 2018
I need to debug a piece of code and couldn't understand what the string in 'DeleteFcn' evaluate to. Also, what would the be the output of DeleteFcn attribute here
if true
c = text('Parent',b, ...
'DeleteFcn','eval(''delete(get(gcbo,''''userdata''''))'','''')', ...
'HandleVisibility','off', ...
'Tag','ColorbarDeleteProxy', ...
'UserData',66.0018, ...
'Visible','off');
end
  2 commentaires
Adam
Adam le 6 Juin 2018
It would appear to delete the 'UserData' field of whatever handle's callback it is that triggers it, which I guess would be the figure, though I never use either eval or gcbo myself and rarely 'UserData'.
Stephen23
Stephen23 le 6 Juin 2018
Modifié(e) : Stephen23 le 6 Juin 2018
'DeleteFcn','eval(''delete(get(gcbo,''''userdata''''))'','''')', ...
Ugh. Badly written code. Do NOT learn from this code. So many levels of bad in just one line. Ugh.
  1. The MATLAB documentation specifically advises against a defining a callback as a string: "Defining a callback as a character vector is not recommended. The use of a function specified as function handle enables MATLAB to provide important information to your callback function." As the documentation recommends, you should use function handles for defining callbacks.
  2. Calling gcbo is superfluous, because when using a function handle the first input argument is a handle to that object.
  3. eval is a chainsaw that some beginners overuse, perhaps because they underestimate the damage that it can cause. The MATLAB documentation has an entire page which advises why evaluating strings should be avoided. Read this to know more:
'UserData',66.0018, ...
4. Hardcoded graphics handles!? This code just gets worse and worse....

Connectez-vous pour commenter.

Réponse acceptée

Stephen23
Stephen23 le 6 Juin 2018
Modifié(e) : Stephen23 le 6 Juin 2018
That is a very badly written piece of code. DO NOT LEARN FROM IT.
Something like this is simpler, clearer, less buggy, and much easier to debug:
'DeleteFcn',@(~,~)delete(get(gcbo,'userdata')),...
Note that because that object's handle is provided anyway, it should probably be something like this:
'DeleteFcn',@(src,~)delete(get(src,'userdata')),...
Explanation: it gets the userdata field from the object and then deletes whatever that is. Presumably the userdata contains some graphics handle/s... Oh, It does: a hardcoded handle value.
Ouch.
This code makes me cry. Using gcbo and a hardcoded handle is a sign that the entire code needs a major revision.

Plus de réponses (0)

Catégories

En savoir plus sur Interactive Control and Callbacks dans Help Center et File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by