patternjavascriptMinor
Knockout selectlist binding
Viewed 0 times
bindingknockoutselectlist
Problem
I've done some tinkering about with Knockout in search for a better solution on how to bind select lists (dropdowns). I came up with a extender in combination with a binding.
Extender:
Binding:
```
var selectListHTML = "";
ko.bindingHandlers.selectList = {
init: function(element, vA, aBA,vm
Extender:
ko.extenders.selectList = function (target, params) {
var result = ko.computed({
read: target,
write: function (newValue) {
if (newValue) {
target(newValue);
} else {
target(undefined);
}
}
});
//add some sub-observables
result.options = $.map(params.options, function (v, k) { return { val: k, txt: v }; });
result.caption = params.caption;
function getInitialEnableValue(){
if(params.hasOwnProperty('enable')){
if($.isFunction(params.enable)){
return params.enable();
}
return params.enable;
}
return true;
}
var isEnabled = ko.observable(getInitialEnableValue());
result.enable = ko.computed({
read: function(){
return isEnabled();
},
write: function(newValue){
if(!newValue) result(undefined);
isEnabled(newValue);
}
});
if(isEnabled() && result.options.length === 1){
result(result.options[0].val);
}
//return the new observable
return result;
};Binding:
```
var selectListHTML = "";
ko.bindingHandlers.selectList = {
init: function(element, vA, aBA,vm
Solution
From a once over:
-
- Your indentation in
ko.extenders.selectList = function (target, params) {should be 4 spaces to make it far more readable
-
write could use a ternary approach:write: function (newValue) {
target( newValue || undefined );
}- This code could use some more/better comment
- JSHint could find nothing wrong with it
- I am not too excited by seeing all those options as part of the HTML, it just feels wrong. None of the tools work for you in this case ( linting, beautifying, even colored syntax ). I guess that's more a reflection on knockout than on your code.
Code Snippets
write: function (newValue) {
target( newValue || undefined );
}Context
StackExchange Code Review Q#15625, answer score: 2
Revisions (0)
No revisions yet.