Search code examples
gwttinymcejsni

GWT JSNI call Java instance method from nested Javascript funcion


I have a simple wrapper around a WYSIWYG editor (TinyMCE). I'm using JSNI to call a Java instance method (onClick) from Javascript. However the Java onClick method always gets called on the same Java instance (the last one created), no matter the editor that originated it.

        private SimplePanel panel;
        private TextArea ta;
        private String id;

        public TinyMCE(AbstractTinyMCEConfiguration config) {       
            id = HTMLPanel.createUniqueId();
            ta = new TextArea();
            ta.getElement().setId(id);
                panel = new SimplePanel();
            panel.add(ta);
            initWidget(panel);
            init(config);
        }

        protected native void init(AbstractTinyMCEConfiguration conf) /*-{
            var ins = this;
            $wnd.tinyMCE.init({
                    // General options
                    mode : [email protected]::getMode()(),
                    setup : function(ed) {
                        ed.onClick.add(function(ed,e) { 
                            alert(ed.id);
                            [email protected]::onClick(Lcom/google/gwt/dom/client/NativeEvent;)(e);
                        }); 
                    }
                }); 
        }-*/;

        private void onClick(NativeEvent e) {
            GWT.log("onClick " + id);
            ClickEvent.fireNativeEvent(e, this);
        }

I'm not sure if I can call a Java method from a Javascript funcion that is inside another funcion. Maybe that explains my problem... or maybe I'm missing something. Thanks for your help.


Solution

  • I think TinyMCE has one shared configuration for all editors, and that is the problem here.

    It probably does not make much sense to hand the configuration to the constructor if it is shared...

    Why not add a static map that maps the id back to the Java instance, something like

        // ....
        private static Map<String, TinyMCE> idMap = new HashMap<String, TinyMCE>();
    
        public TinyMCE() {       
            // ...
            idMap.put(id, this);
        }
    
        // call this from Javascript with (ed.id, e)
        private static void onClick(String id, NativeEvent e) {
          idMap.get(id).onClick(e);
        }