Search code examples
javajavascriptjquerytapestry

Assigning/Passing value from Java function to JS/JQuery function


Lets say I have a Java function something like

public int getNumber(){

}

which returns some value based on it's logic. And I have a JS file something like

Tapestry.Validator.amountValidator = function(field, message) {

    field.addValidator(function(value) {
        if (value != null) {
          // code here
            }
        }
    });

};

Now I am asking myself is it possible in JS or JQuery to pass value from Java function to it's function(value) in JS and if so, how can it be achieved?

UPDATE: As suggested by abalos answer, Tap for myself has already done 3 out of 4 stages for it. I am providing a function that deals with server side and logic behind it.

   @InjectComponent
    private TextField amount;
    @Inject
    private FieldValidatorSource fieldValidatorSource;

    public FieldValidator<?> getAmountValidator() 
     {
        return fieldValidatorSource.createValidators(amount, "required,max=" + getBroj());
    }

Now here validator is taken from a logic inside a function getBroj(), which is maximum number of what it takes. And this works like a charm on server side. Now I was thinking that what I don't have( using my logic ) is only Client side, and I can achieve it by updating current Validation class from Tapestry that will handle with this kind of request yet known to that class. And to do it I would need to call a js file with a function calling something like above in the example, but I am not quite sure how to pass value from getNumber() function to the JS function above.


Solution

  • You don't need Jersey or DWR or any other framework at all for invoking a method in Tapestry. You just need to ask your questions properly.

    final private static String EVENT_NAME = "whateverEventNameYouWant";
    
    @Inject
    private ComponentResources resources;
    
    @Inject
    private JavaScriptSupport javaScriptSupport;
    
    /** Method that will provide the value you want to pass to JS. */
    @OnEvent(EVENT_NAME) 
    public JSONObject provideValue() {
        JSONObject object = new JSONObject();
        object.put("value", /* the value you want to pass to JS */);
        // other values you may want to pass
        return object;
    }
    
    void afterRender() {
        // This creates an URL for the event you created. Requesting it will
        // invoke any event handler methods for that event name.
        Link link = resources.createEventLink(EVENT_NAME);
        javaScriptSupport.addScript("var eventUrl = '%s';", link.); // the JavaScript variable name doesn't matter. You can choose any you want
    }
    

    Then, in your JavaScript, do an AJAX request using the URL in the eventUrl variable. I'll leave this part for you to figure out from the jQuery documentation. The received data is exactly the JSONObject or JSONArray you'll return in your event handler method.