0

我有一个第 3 方自定义 jquery 组件,它覆盖了一个复选框并为它提供了一个更漂亮的“切换”外观。该组件有一个函数回调,只要用户单击该组件就会发生。

我如何使用事件目标设置可观察值,而不知道具体在我的视图模型中调用事件的哪个属性。

例如:

html是:

<input type="checkbox" id="cb123" data-bind="checked: IsDeleted" />
<input type="checkbox" id="cb345" data-bind="checked: IsValid" />

Javascript 回调如下所示:

$(document).ready(function() {
     .... Code snipped  ....
     var viewModel = ko.mapping.fromJS(myModel);
     ko.applyBindings(viewModel);

      $(':checkbox').toggleCheckbox({
           onChange: function($el, value, e) {
              var ctx = ko.contextFor(e.target);    // Gets me the knockout context object.

              // How do I set the appropriate observable value from here?
              // In this case either one of the checkboxes could have been triggered.
           }
      });
});  

任何帮助,将不胜感激。

4

2 回答 2

1

获取 observable 的一种方法是解析 data-bind 属性本身:

// inside your event handler
var viewModel = ko.dataFor(e.target);
var bindValue = $(e.target).data('bind');
// in case you applied 'checked' binding only: data-bind="checked: IsDeleted"
var observableName = $.trim(bindValue.split(':')[1]);

// get value
var _value = viewModel[observableName]();
// set value: viewModel[observableName](newValue);
于 2013-01-16T19:49:21.490 回答
0

考虑使用自定义 bindingHandler 来初始化 toggleCheckbox。

<input type="checkbox" id="cb123" data-bind="toggleCheckboxChecked: IsDeleted" />
<input type="checkbox" id="cb345" data-bind="toggleCheckboxChecked: IsValid" />

Javascript:

ko.bindingHandlers.toggleCheckboxChecked = {
   init: function (element, valueAccessor) {
       // This is just to set the initial value of the checkbox
       element.checked = ko.utils.unwrapObservable(valueAccessor());

       // Then turn the element into an enhanced checkbox
       $(element).toggleCheckbox({
           onChange: function($el, value, e) {
              var checkedBinding = valueAccessor();
              checkedBinding(value);
           }
       });
   },
   update: function (element, valueAccessor) {
       // this is invoked by knockout when checkedBinding changes, so
       // to get a two-way-binding you need to update the checkbox component
       // here with ko.utils.unwrapObservable(valueAccessor())
   }
}

官方页面上有一些关于自定义绑定处理程序的信息,但我也推荐 rniemeyer 的博客,尤其是这篇文章

于 2013-01-17T19:01:02.560 回答