Tuesday 22 January 2013

How to wrap Javascript libarary in Vaadin

Hello,
    Last days I was implementing some Vaadin wrapper for custom Javascrip library. In this post I want share some knowledge how wrap JS library as Vaadin widget.

    Before start please check this article(https://vaadin.com/book/-/page/gwt.html). It contains basic information about development of the custom widgets in Vaadin.

    Assume we want to wrap simple Javascrip library which alerts and returns some message string.
    It will have one function:

  function proceedMessage(message) {
   alert(message);
   return message;
  }

     To wrap this library we have to create basic vaadin project named vaadin-js-wrap. It can be done with vaadin eclipse plugin as described in article above. It will have next folder organisation:



     As you can see we put our javascript library to public/jswrapper folder.
     Also script should be add to widget set xml:
     
       
        
     
      Next step is to create JavaScript Native Interface (JSNI) class which will allow us to call proceedMessage function form Java code. Here  you can find information about this interface. In short this interface allows you to invoke and execute Javascript code form Java and vise versa.
     Here is code for class used in application:
public class MessageJSNI {

   protected MessageJSNI() {
   }

   public native static String proceedMessage(String message) /*-{
       return $wnd.proceedMessage(message);
   }-*/;
  }
   
     Let's look to classes MessageField and VMessageField:  
        MessageField class takes as parameter message string wich will be shown. To pass it to frontend part method paintContent is used:
@Override
  public void paintContent(PaintTarget target) throws PaintException {
   super.paintContent(target);

   // Paint any component specific content by setting attributes
   // These attributes can be read in updateFromUIDL in the widget.
   target.addAttribute("message", message);
  }
        VMessageField is frontend representation of our field, it reads message in updateFromUIDL method:
String message = uidl.getStringAttribute("message");
      and invokes MessageJSNI.proceedMessage:
getElement().setInnerHTML(MessageJSNI.proceedMessage(message));

       MessageJSNI will call our script.js proceedMessage function which will show alert message and return passed string.

 After widgetsets compilation, MessageField can be used as standart vaadin component:
Window mainWindow = new Window("Vaadin JS Wrapper Application");
  MessageField messageField = new MessageField("Hello world!");
  mainWindow.addComponent(messageField);
  setMainWindow(mainWindow);

   Result of application:



 Here you can find sources.

 BR,
 Paul Butenko

No comments:

Post a Comment