Google Closure Library – Hello World, Event, $
Hello World
hello.html
<html>
<head>
<script src="goog/base.js"></script>
<script src="hello.js"></script>
</head>
<body onload="sayHi()">
</body>
</html>
hello.js
goog.require('goog.dom');
function sayHi() {
var newHeader = goog.dom.createDom('h1', {'style': 'background-color: #EEE'},
'Hello world!');
goog.dom.appendChild(document.body, newHeader);
}
ライブラリの読み込むファイルが、goog/base.jsだけってところがいいですね。
イベントリスナー
ロード時に何かする
goog.events.listen(window, goog.events.LOAD, function(e) {
alert('onload!');
});
ID:button1をクリックしたときに何かする
goog.events.listen(goog.dom.$('button1'), goog.events.CLICK, function(e) {
alert('button1 clicked!');
});
ちなみに、定義されているイベントタイプは以下の通り。
/**
* Constants for event names.
* @enum {string}
*/
// TODO: Move to its own file.
goog.events.EventType = {
// Mouse events
CLICK: 'click',
DBLCLICK: 'dblclick',
MOUSEDOWN: 'mousedown',
MOUSEUP: 'mouseup',
MOUSEOVER: 'mouseover',
MOUSEOUT: 'mouseout',
MOUSEMOVE: 'mousemove',
SELECTSTART: 'selectstart', // IE, Safari, Chrome
// Key events
KEYPRESS: 'keypress',
KEYDOWN: 'keydown',
KEYUP: 'keyup',
// Focus
BLUR: 'blur',
FOCUS: 'focus',
DEACTIVATE: 'deactivate', // IE only
// TODO: Test these. I experienced problems with DOMFocusIn, the event
// just wasn't firing.
FOCUSIN: goog.userAgent.IE ? 'focusin' : 'DOMFocusIn',
FOCUSOUT: goog.userAgent.IE ? 'focusout' : 'DOMFocusOut',
// Forms
CHANGE: 'change',
SELECT: 'select',
SUBMIT: 'submit',
// Misc
CONTEXTMENU: 'contextmenu',
DRAGSTART: 'dragstart',
ERROR: 'error',
HASHCHANGE: 'hashchange',
HELP: 'help',
LOAD: 'load',
LOSECAPTURE: 'losecapture',
READYSTATECHANGE: 'readystatechange',
RESIZE: 'resize',
SCROLL: 'scroll',
UNLOAD: 'unload'
};
DOM操作
document.getElementByIdは、goog.dom.$(‘id’)のようにやる。
実際のソースではこうなっている。
/**
* Alias for getElementById. If a DOM node is passed in then we just return
* that.
* @param {string|Element} element Element ID or a DOM node.
* @return {Element} The element with the given ID, or the node passed in.
*/
goog.dom.getElement = function(element) {
return goog.isString(element) ?
document.getElementById(element) : element;
};
/**
* Alias for getElement.
* @param {string|Element} element Element ID or a DOM node.
* @return {Element} The element with the given ID, or the node passed in.
* @deprecated Use {@link goog.dom.getElement} instead.
*/
goog.dom.$ = goog.dom.getElement;
参考リンク




