Showing posts with label json. Show all posts
Showing posts with label json. Show all posts

Wednesday, March 21, 2012

Knockout JS AutoComplete Binding with multiple selections

The following custom binding can be used to bind data to the jQuery UI autocomplete widget and allow multiple selections;

    ko.bindingHandlers.autocomplete_multiselect = {
        init: function (element, params) {
            var options = params().split(' ');
            $(element).bind("focus", function () {
                $(element).change();
            });
            $(element).autocomplete({ source: function (request, response) {
                $.getJSON(options[0], { q: extractLast(request.term) }, function (data) {
                    response($.map(data, function (item) {
                        return { label: item[options[1]], value: item[options[2]] };
                    }));
                });
            },
                focus: function () {
                    // prevent value inserted on focus
                    return false;
                },
                select: function (event, ui) {
                    var terms = split(this.value);
                    // remove the current input
                    terms.pop();
                    // add the selected item
                    terms.push(ui.item.value);
                    // add placeholder to get the comma-and-space at the end
                    terms.push("");
                    this.value = terms.join(", ");
                    return false;
                }
            })
        .bind("focus", function () {
            $(element).change();
        });
        },
        update: function (element, params) {
        }
    };


Use it in the following way;
<input type="text" data-bind="value: Categories, autocomplete_multiselect: 'AutoCompleteDataSourceUrl ItemName ItemValue'" />
Where AutoCompleteDataSourceUrl should be replaced by the URL of the service returning autocomplete data. ItemName and ItemValue should be replaced by the names of the name and value fields in the returned json.



Knockout JS AutoComplete Binding

The following custom binding can be used to bind data to the jQuery UI autocomplete widget;

    ko.bindingHandlers.autocomplete = {
        init: function (element, params) {
            var options = params().split(' ');
            $(element).bind("focus", function () {
                $(element).change();
            });
            $(element).autocomplete({ source: function (request, response) {
                $.getJSON(options[0], { q: request.term }, function (data) {
                    response($.map(data, function (item) {
                        return { label: item[options[1]], value: item[options[2]] };
                    }));
                });
            }
            });
        },
        update: function (element, params) {
        }
    };

Use it in the following way;
<input type="text" data-bind="value: Category, autocomplete: 'AutoCompleteDataSourceUrl ItemName ItemValue'" />
Where AutoCompleteDataSourceUrl should be replaced by the URL of the service returning autocomplete data. ItemName and ItemValue should be replaced by the names of the name and value fields in the returned json.

Monday, March 19, 2012

Knockout JS DatePicker Binding

If you are binding to JSON data using Knockout.js, chances are that you may have encountered problems using the jquery ui datepicker control. The following knockout custom binding can be used to handle dates properly with knockout.js and the datepicker control.

    ko.bindingHandlers.datepicker = {
        init: function (element, valueAccessor, allBindingsAccessor) {
            try {
                var jsonDate = ko.utils.unwrapObservable(valueAccessor());
                var value = parseJsonDateString(jsonDate);
                var strDate = value.getMonth() + 1 + "/"
                                + value.getDate() + "/"
                                + value.getFullYear();
                element.setAttribute('value', strDate);
            }
            catch (exc) {
            }
            //initialize datepicker with some optional options
            $.datepicker.setDefaults({ dateFormat: 'mm/dd/yy' });
            var options = allBindingsAccessor().datepickerOptions || dateTimePickerOptions;
            $(element).datepicker(options);

            //handle the field changing
            ko.utils.registerEventHandler(element, "change", function () {
                var observable = valueAccessor();
                var dt = new Date($(element).val());
                observable('/Date(' + dt.getTime() + ')/');
            });

            //handle disposal (if KO removes by the template binding)
            ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                $(element).datepicker("destroy");
            });
        },
        update: function (element, valueAccessor) {
            var val = valueAccessor();
            var dt = new Date(element.getAttribute('value'));
            val('/Date(' + dt.getTime() + ')/');
        }
    };

var jsonDateRE = /^\/Date\((-?\d+)(\+|-)?(\d+)?\)\/$/;

var parseJsonDateString = function (value) {
    var arr = value && jsonDateRE.exec(value);
    if (arr) {
        return new Date(parseInt(arr[1]));
    }
    return value;
};

Saturday, March 10, 2012

JSON dates and Knockout.js date binding

JSON data for date data types is returned as a string in the following format;

\/Date(1330731072583)\/

If you are using Knockout.js for client-side data binding, a simple value binding will result in the same date string being displayed on the data bound control. To properly handle this a custom date binding can be created.

ko.bindingHandlers.date = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        try {
            var jsonDate = ko.utils.unwrapObservable(valueAccessor());
            var value = parseJsonDateString(jsonDate);
            var strDate = value.getMonth() + 1 + "/"
                            + value.getDate() + "/" 
                            + value.getFullYear();
            element.setAttribute('value', strDate);
        }
        catch (exc) {
        }
        $(element).change(function () {
            var value = valueAccessor();
            value(element.getAttribute('value'));
        });
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var val = valueAccessor();
        val(element.getAttribute('value'));
    }
};
The parseJsonDateString function can be defined using a regular expression.

var jsonDateRE = /^\/Date\((-?\d+)(\+|-)?(\d+)?\)\/$/;
var parseJsonDateString = function (value) {
    var arr = value && jsonDateRE.exec(value);
    if (arr) {
        return new Date(parseInt(arr[1]));
    }
    return value;
};

Use the date binding in the following way;
<input type="text" id="StartDateText" data-bind="date: StartDate" />