Is there any way of improving this code? (Here's a JSFiddle with an example and comments)
Example: A hotel greeter can greet guests and accepts tips, but it's impossible to see the total of tips a greeter has received.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<pre>
[]___
/ /\ O <span id="alfred-says"><!-- the view --></span>
/____/__\ /|\
|[][]|||| / \
ALFRED
</pre>
<button onclick="javascript:alfred('greet')">Arrive at Hotel</button>
<button onclick="javascript:alfred('acceptTip', 10)">Tip Alfred $10</button>
<script>
var HOTEL, alfred;
HOTEL = {}; // Namespace
(function (HOTEL) {
// Reuseable controller
var controllerPrototype = {
greet: function () {
this.model.view.innerHTML = '"' + this.model.greeting + '"';
},
acceptTip: function (tip) {
this.model.tips += tip;
this.model.view.innerHTML = '"' + this.model.thankyou + '"';
}
};
// Create a new greeter
HOTEL.newGreeter = function (view) {
var controller = Object.create(controllerPrototype);
controller.facet = function () {
var args, method;
method = arguments[0];
args = 2 <= arguments.length ? [].slice.call(arguments, 1) : [];
if (method === "facet" || method === "model" || (controller[method] == null)) {
return undefined;
}
// Model, View and real Controller are never exposed
return controller[method].apply(controller, args);
};
controller.model = {
greeting: "Hello",
thankyou: "Thank you",
tips: 0,
view: view
};
return controller.facet;
};
}(HOTEL));
// Alfred only exposes the controller facet. His tips are a secret...
alfred = HOTEL.newGreeter(document.getElementById("alfred-says"));
</script>
</body>
</html>
Goals:
- Keep it DRY
- Keep it MVC
- Make sure anyone with access to a "greeter" can never manipulate the view or model directly.
Limitations:
- To avoid clutter, avoid type checking to avoid simple errors unless it is necessary to guarantee integrity.
Some specific thoughts:
- Is there a better way of passing model and view into the controller?
- Is there a better way of communicating with the controller?
- Is there a good way of making a more general view?
- Any other improvements?