GWT: Checking if event handler exists
I'm using a key up handler to add and remove event handlers depending on the string value of a text box. I wouldn't want to add or remove an event handler on every key up. 开发者_如何学PythonHow do I first check if a handler already exists?
HandlerRegistration firstHandler = null;
HandlerRegistration secondHandler = null;
public void onKeyUp(KeyUpEvent event) {
if (countSpaceChar(textBox.getText()) == 0) {
// code to check if MyFirstHandler is already attached?
firstHandler = textBox.addKeyUpHandler(new MyFirstHandler(this));
} if (countSpaceChar(textBox.getText()) == 1) {
firstHandler.removeHandler();
// code to check if MySecondHandler is already attached?
secondHandler = textBox.addKeyUpHandler(new MySecondHandler(this));
}
}
if (firstHandler != null)
will do the job, and when you remove handler, null it registration:
firstHandler.removeHandler();
firstHandler = null;
精彩评论