如何访问自定义敲除绑定中的变量

How to access variables inside custom knockout binding

所以我正在使用这个日期选择器库。 http://eonasdan.github.io/bootstrap-datetimepicker/Installing/#knockout

有没有办法让我从处理程序中获取值并将其保存在我的视图模型中?我想在我的视图模型内的处理程序外部公开 var picker = $(element).data('DateTimePicker'); 的值。这可能吗?

/*globals Hilary*/
Hilary.scope('learn').register({
    name: 'DatetimeVM',
    dependencies: ['ko', 'jQuery', 'moment', 'OptionSelectVM'],
    factory: function (ko, $, moment, OptionSelectVM) {
        'use strict';

        return function (date) {
            var self = {
                date: {
                    type: ko.observable(),
                    start: ko.observable(),
                    end: ko.observable()
                }
            };

            if(!ko.bindingHandlers.dateTimePicker) {
                ko.bindingHandlers.dateTimePicker = {
                    init: function (element, valueAccessor, allBindingsAccessor) {
                        //initialize datepicker with some optional options
                        var viewOptions = allBindingsAccessor().dateTimePickerOptions || {},
                            options;

                        options = $.extend({
                            inline: true,
                            debug: true
                        }, viewOptions);

                        $(element).datetimepicker(options);

                        //when a user changes the date, update the view model
                        ko.utils.registerEventHandler(element, 'dp.change', function (event) {
                            var value = valueAccessor();
                            if (ko.isObservable(value)) {
                                if (event.date !== null && !(event.date instanceof Date)) {
                                    value(event.date.toDate());
                                } else {
                                    value(event.date);
                                }
                            }
                        });

                        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
                            var picker = $(element).data('DateTimePicker');

                            if (picker) {
                                picker.destroy();
                            }
                        });
                    },
                    update: function (element, valueAccessor) {
                        var picker = $(element).data('DateTimePicker');

                        //when the view model is updated, update the widget
                        if (picker) {
                            var koDate = ko.utils.unwrapObservable(valueAccessor());

                            //in case return from server datetime i am get in this form for example /Date(93989393)/ then fomat this
                            // koDate = (typeof (koDate) !== 'object') ? new Date(parseFloat(koDate.replace(/[^0-9]/g, ''))) : koDate

                            picker.date(koDate);
                        }
                    }
                };
            }

            return self;
        };
    }
});

是的,你可以!查看 the custom bindings documentation,传递给绑定处理程序的 initupdate 函数的参数比您当前使用的要多,包括第四个名为 viewModel 的预挖空 3.x,以及 3.x 版本的 bindingContext

来自提到的文档:

  • viewModel — This parameter is deprecated in Knockout 3.x. Use bindingContext.$data or bindingContext.$rawData to access the view model instead.
  • bindingContext — An object that holds the binding context available to this element’s bindings. This object includes special properties including $parent, $parents, and $root that can be used to access data that is bound against ancestors of this context.

请注意,这会创建一个依赖关系 你的处理程序 特定的视图模型,这通常是一个危险信号恕我直言。在绑定处理程序应该知道的当前视图模型上显式传递可观察对象或回调可能会更好,因此您可以编写例如:

<div data-bind="datepicker: { date: myDate, additionalData: someObservable }"></div>