summaryrefslogtreecommitdiffstats
path: root/src/com/vaadin/ui/JavascriptManager.java
blob: 72295dce2b5ef8b5ab93d057be796f413a843f9c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/* 
@VaadinApache2LicenseForJavaFiles@
 */

package com.vaadin.ui;

import java.util.HashMap;
import java.util.Map;

import com.vaadin.external.json.JSONArray;
import com.vaadin.external.json.JSONException;
import com.vaadin.terminal.AbstractExtension;
import com.vaadin.terminal.gwt.client.communication.ServerRpc;
import com.vaadin.terminal.gwt.client.extensions.javascriptmanager.JavascriptManagerState;

public class JavascriptManager extends AbstractExtension {
    private Map<String, JavascriptCallback> callbacks = new HashMap<String, JavascriptCallback>();

    // Can not be defined in client package as this JSONArray is not available
    // in GWT
    public interface JavascriptCallbackRpc extends ServerRpc {
        public void call(String name, JSONArray arguments);
    }

    public JavascriptManager() {
        registerRpc(new JavascriptCallbackRpc() {
            public void call(String name, JSONArray arguments) {
                JavascriptCallback callback = callbacks.get(name);
                // TODO handle situation if name is not registered
                try {
                    callback.call(arguments);
                } catch (JSONException e) {
                    throw new IllegalArgumentException(e);
                }
            }
        });
    }

    @Override
    public JavascriptManagerState getState() {
        return (JavascriptManagerState) super.getState();
    }

    public void addCallback(String name, JavascriptCallback javascriptCallback) {
        callbacks.put(name, javascriptCallback);
        if (getState().getNames().add(name)) {
            requestRepaint();
        }
    }

    public void removeCallback(String name) {
        callbacks.remove(name);
        if (getState().getNames().remove(name)) {
            requestRepaint();
        }
    }

}