What does the string in 'DeleteFcn' evaluate to?

3 次查看(过去 30 天)
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 个评论
Adam
Adam 2018-6-6
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 2018-6-6
编辑:Stephen23 2018-6-6
'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....

请先登录,再进行评论。

采纳的回答

Stephen23
Stephen23 2018-6-6
编辑:Stephen23 2018-6-6
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.

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Entering Commands 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by