Ok so I’ve been following KnockoutJS for a while but I haven’t taken the time to play with it yet. Regardless, I recently noticed the extensibility to create custom bindings. (see this)
So, first thing I thought of, was how could I channel my inner-laziness in order to abuse utilize this.
So. I thought about it for a while, and I had a “Switch” statement floating in my head for a while until I ran across a post from Elijah Manor about a kind of strategy pattern in JavaScript.
I thought it was awesome. But even after reading the eval statement disclaimer, I’m still a little uneasy about using it….
YUCK!!
Regardless, I’ll let you be the judge. Here’s a rough excerpt of what I’m talking about.
HTML:
1: <button data-bind="jqui: button">BUTTON OF AWESOME</button>
JavaScript:
1: ko.bindingHandlers.jqui = {
2: init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
3: awesome.handleJqui(element, valueAccessor);
4: }
5: };
6:
7: (function () {
8:
9: function getJquiMethod(element, method) {
10: // EVIL DON'T LOOK AT IT!
11: return eval("setJqui" + method() + "Element");
12: };
13:
14: var setJquiButtonElement = function(element) {
15: $(element).button();
16: };
17:
18: var awesome = {
19: handleJqui: function(element, methodCall) {
20: var fnc = getJquiMethod(element, methodCall);
21: fnc(element);
22: }
23: };
24:
25: window.awesome = awesome;
26:
27: var viewModel = {};
28: ko.applyBindings(viewModel);
29: })();
This allows me to extend at will with functions like
1: var setJquiDatepickerElement = function(element) {
2: $(element).datepicker();
3: }
Which then allows me to call simple stuff like
1: <input type="text" data-bind="jqui: Datepicker" />
Or…Lets get crazy… Let’s say we use the full power of KnockoutJS setup extra parameters to be passed in. Then let’s take that a bit further, and if we’re using ASP.NET MVC 3, we setup some helper methods to create this things for us. Then we can simply make calls like:
1: @Html.DatePickerFor(a => a.BirthDate)
Cheating?! I think so. But time saver? Definately. My question is, is this too much of a hack? My problem primarily focuses around the eval call, in addition to the current method if extensibility with these calls.
You be the judge! As for me, the project I’m working on right now is small enough that I’m not caring right now.
Worst case, I hope you learned something!
-Jeff