KnockoutJS - 如何一般更新可观察值

时间:2013-01-16 17:01:28

标签: knockout.js knockout-2.0 ko.observablearray

我有一个第三方自定义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.
           }
      });
});  

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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())
   }
}

official page上有一些关于自定义绑定处理程序的信息,但我也推荐rniemeyer的博客,特别是this post