1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 package org.htmlunit.javascript.host.event;
16
17 import org.htmlunit.corejs.javascript.BaseFunction;
18 import org.htmlunit.corejs.javascript.Context;
19 import org.htmlunit.corejs.javascript.Function;
20 import org.htmlunit.corejs.javascript.JavaScriptException;
21 import org.htmlunit.corejs.javascript.Scriptable;
22 import org.htmlunit.html.DomNode;
23
24
25
26
27
28
29
30 public class EventHandler extends BaseFunction {
31 private final DomNode node_;
32 private final String eventName_;
33 private final String jsSnippet_;
34 private Function realFunction_;
35
36
37
38
39
40
41
42 public EventHandler(final DomNode node, final String eventName, final String jsSnippet) {
43 super();
44 node_ = node;
45 eventName_ = eventName;
46 jsSnippet_ = jsSnippet;
47 }
48
49
50
51
52 @Override
53 public Object call(final Context cx, final Scriptable scope,
54 final Scriptable thisObj, final Object[] args)
55 throws JavaScriptException {
56
57
58
59
60
61
62
63
64 if (realFunction_ == null) {
65 final String js = "function on" + eventName_ + "(event) { " + jsSnippet_ + " \n}";
66 realFunction_ = cx.compileFunction(thisObj, js, eventName_ + " event for " + node_
67 + " in " + node_.getPage().getUrl(), 0, null);
68 realFunction_.setParentScope(thisObj);
69 }
70
71 return realFunction_.call(cx, scope, thisObj, args);
72 }
73
74
75
76
77
78
79 @Override
80 public Object getDefaultValue(final Class<?> typeHint) {
81 return "function on" + eventName_ + "(event) { " + jsSnippet_ + " }";
82 }
83
84
85
86
87 @Override
88 public Object get(final String name, final Scriptable start) {
89
90 if ("toString".equals(name)) {
91 return new BaseFunction() {
92 @Override
93 public Object call(final Context cx, final Scriptable scope,
94 final Scriptable thisObj, final Object[] args) {
95 return "function on" + eventName_ + "(event) { " + jsSnippet_ + " }";
96 }
97 };
98 }
99
100 return super.get(name, start);
101 }
102 }