Uncategorized
-
Alternative Approach to Extenders in Knockout.js
ko.observable.fn.booleanValue = function () { var formattedValue = ko.computed({ read: function () { if (this() === true) return "True"; else if (this() === false) return "False"; }, write: function (newValue) { if (newValue) { if (newValue === "False") this(false); else if (newValue === "True") this(true); } } }, this); this.formattedValue = formattedValue; this.formattedValue(this()); return this; };
This code is an alternative to the previous post of how to do an extender for a Boolean value. It works exactly like the extender, but instead attaches functionality to the .fn extension point of ko.observable. To use this, do the following:
this.wantsFriesWithThat = ko.observable(true).booleanValue();
This is a bit cleaner than using the extend() method. If we wanted, we could send in parameters to further configure how this extension works, we could simply pass them to the booleanValue() function. If you want to add another extender, you would simply chain another onto the call to booleanValue(). This is why the function returns this because the this in the function refers to the observable itself.Categories: Uncategorized
-
About This Blog
Hello World! In this blog, I’m going to post snippets of code and things that I think are cool or useful to other people. I’ve learned a lot from many other blogs out there and it is time for me to contribute something back.
I mostly develop for the .NET platform with C#, but I also do quite a bit of JavaScript development and general web stuff. Hopefully you will find something useful here as I get around to posting things over time.
Categories: Uncategorized
- 1