About timer object and StartFcn

7 次查看(过去 30 天)
Roy Hamdan
Roy Hamdan 2016-1-29
编辑: Guillaume 2016-1-30
What does the @(x,y) mean in this phrase: t = timer('TimerFcn',@(x,y)disp('Hello World!'),'StartDelay',5);

回答(1 个)

Walter Roberson
Walter Roberson 2016-1-29
The great majority of callbacks in MATLAB are called with two automatically supplied arguments.
The first argument is the handle to the object which the callback is about; this allows you to use the same callback function for multiple objects and still reference the appropriate object.
The second argument is either empty (most common) or a struct . The content of the struct will provide details about what triggered the callback. For example KeyPressFcn callbacks get an event structure that indicates which key was pressed.
It happens that the timer object callbacks never need to be passed additional information of this sort, so for them the second parameter is always empty, [] . MATLAB provides the argument even if it is empty in order to provide a uniform interface. It is not required that you do anything with either parameter.
(The exception to this organization are the few "callbacks" that are used as filters, such as position constraint functions and datacursormode datatip construction functions; these few functions return values whereas regular callbacks that follow the standard scheme never return values.)
  3 个评论
Walter Roberson
Walter Roberson 2016-1-29
"Why do we use @(x,y)"
Arbitrary dummy parameter names. It would have meant the same thing to write @(source,event) or @(hObject,evt) .
In the case where the parameters are being ignored, @(~,~) is fine too. It is just a newer syntax not supported by sufficiently old MATLAB. There hasn't been any point in going back to edit the examples to use ~
Guillaume
Guillaume 2016-1-30
编辑:Guillaume 2016-1-30
Calling the callback arguments x and y is very silly. Using variable names that represent what they actually contain is a big aid in making the program easy to understand.
In many languages, .Net in particular, there is always two arguments for an event ( == callback), the source that generated the event and an object that represent the event properties (coordinates for a mouse click, key pressed for a key event, etc.).
Matlab follows the same pattern except that often it actually doesn't put anything in the event property (a wasted opportunity if you ask me).
If you are not going to ignore the event arguments (with @(~, ~)), I'd recommend you call them source and eventargs. That is the convention in many other languages.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Interactive Control and Callbacks 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by