Hi,
You can extend existing instance of TextField using Vaadin component Extensions. An extension is an additional object that can be attached to a component and execute some JavaScript in a browser.
You can read more about Extensions here: Integrating JavaScript Components and Extensions | Client-Server Integration | Framework | Vaadin 8 Docs
In a case of CUBA application, you can use this mechanism in web modules. Let assume I want to create simple input listener that will show browser alert.
First, I create Java class MyExtension that will extend AbstractJavaScriptExtension class from Vaadin:
@JavaScript("vaadin://my-extension.js")
public class MyExtension extends AbstractJavaScriptExtension {
public MyExtension(TextField target) {
super(target);
callFunction("init", target.getId());
}
}
Here I call “init” function from my javascript file and pass “id” of target TextField as a parameter.
Next, I create JavaScript file in modules/web/web/VAADIN/ with name my-extension.js:
window.com_company_demo_web_ext_MyExtension = function() {
var self = this;
self.init = function (inputId) {
$('#' + inputId).on('input', function() {
window.alert('Changed!');
});
}
}
There I define the function with a special name; it should be equal to FQN of my Java class. Also, I define “init” function with one parameter inputId. Then I subscribe to “input” events to show alerts on input in my TextField.
And finally, I create my extension in a screen using Vaadin component, obtained from CUBA component (see unwrap method):
public class ExtAppMainWindow extends AppMainWindow {
@Inject
protected TextField extTextField;
@Override
public void init(Map<String, Object> params) {
super.init(params);
com.vaadin.ui.TextField vTextField = extTextField.unwrap(com.vaadin.ui.TextField.class);
vTextField.setId("myExtendedInput" + RandomUtils.nextInt(100000)); // we need id to find our input in JS
new MyExtension(vTextField);
}
}
Now, if I type one char in my TextField, I will see browser alert. As you see, I haven’t created any new component, I’ve just added new functionality to the existing instance of TextField.
I’ve prepared simple demo for you, see project on github GitHub - cuba-labs/js-extension: Example of extending of existing UI component using JavaScript extension.