Skip to content

Instantly share code, notes, and snippets.

@mryellow
Created May 27, 2015 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mryellow/6b2bf67e91d91f54d250 to your computer and use it in GitHub Desktop.
Save mryellow/6b2bf67e91d91f54d250 to your computer and use it in GitHub Desktop.
KnockoutJS binding handlers
/**
* KnockoutJS Binding handler to select from array correct index based on stored key.
* This allows a model with `model_id` set to properly select the correct option after binding, when they become available.
*/
ko.bindingHandlers.optionsSelect = {
init: function(element, valueAccessor, allBindingsAccessor, deprecated, bindingContext) {
//console.log('optionsSelect: ', ko.unwrap(valueAccessor()), ko.unwrap(allBindingsAccessor()), bindingContext);
var input = ko.unwrap(valueAccessor().input);
var output = ko.unwrap(valueAccessor().output);
var condition = ko.unwrap(valueAccessor().condition);
var options = ko.unwrap(allBindingsAccessor().options);
if (input && options && output) {
bindingContext.$data[output] = ko.utils.arrayFirst(options, function(item) {
if (condition) {
var match = null;
ko.utils.objectForEach(condition, function(key, val) {
if (match !== false) match = (input[key] === item[val]);
});
return match;
} else {
return (item._id === input);
}
});
// We're doing initial setup, reset dirty.
if (bindingContext.$data._isDirty !== undefined) bindingContext.$data._isDirty = false;
if (bindingContext.$parent._isDirty !== undefined) bindingContext.$parent._isDirty = false;
}
}
};
/**
* KnockoutJS Binding Handler for jQuery-UI date-picker initalisation.
*/
ko.bindingHandlers.datePicker = {
init: function(element, valueAccessor, allBindingsAccessor, deprecated, bindingContext) {
$(element).datepicker({
dateFormat: '@' // Unix Epoch in miliseconds.
});
}
};
@mryellow
Copy link
Author

mryellow commented Jul 1, 2015

<select data-bind="options: estimations,
    optionsText: function(item) {
        if (item && item.full_name) {
            return item.full_name;
        }
    },
    optionsSelect: {
        input: estimation,
        output: 'estimation',
        condition: {
            full_name:  'full_name'
        },
        options: estimations
    },
    value: estimation,
    optionsCaption: '...'">
</select>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment