Skip to content

Instantly share code, notes, and snippets.

@pinne
Last active February 5, 2016 09:49
Show Gist options
  • Save pinne/0fdf712a3e15c9bed3b3 to your computer and use it in GitHub Desktop.
Save pinne/0fdf712a3e15c9bed3b3 to your computer and use it in GitHub Desktop.
"use strict";
var app = app || {};
"use strict";
(function () {
var Widget = app.Widget;
var Button = app.Button = function (className, label) {
Widget.apply(this, arguments);
this.el = document.createElement('button');
this.label = label;
this.el.innerHTML = label;
this.el.className = className;
};
Button.prototype = Object.create(Widget.prototype);
Button.prototype.log = function (id) {
document.getElementById(id).innerHTML += this.label;
};
})();
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Javascript objects</title>
<script src="app.js"></script>
<script src="Widget.js"></script>
<script src="Button.js"></script>
<script src="main.js"></script>
</head>
<body>
<div id="buttons"></div>
<div id="log-1" class="log"></div>
<div id="log-2" class="log"></div>
</body>
</html>
"use strict";
(function () {
var Widget = app.Widget;
var Button = app.Button;
window.onload = function () {
var b1 = new Button('first', 'One');
b1.on('click', function () {
this.log('log-1');
}.bind(b1));
b1.render(document.getElementById('buttons'));
b1.css({
'background': '#ddf'
});
var b2 = new Button('second', 'Two');
b2.on('click', function () {
this.log('log-2');
}.bind(b2));
b2.render(document.getElementById('buttons'));
b2.css({
'background': '#dfd'
});
}
})();
"use strict";
(function () {
var Widget = app.Widget = function (width, height, className) {
this.width = width;
this.height = height;
this.className = className;
};
Widget.prototype.render = function (attachPoint) {
if (this.el) {
this.el.width = this.width;
this.el.height = this.height;
this.className = this.className;
attachPoint.appendChild(this.el);
}
};
Widget.prototype.on = function (evt, fn) {
if (this.el) {
this.el.addEventListener(evt, fn);
}
};
Widget.prototype.css = function (styles) {
if (!this.el) {
return;
}
var styleNames = Object.keys(styles);
var el = this.el;
[].forEach.call(styleNames, function (stylename) {
el.style[styleNames] = styles[styleNames];
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment