2013-03-05 88 views
0

請參閱hereKnockout如何將對象綁定到複選框和收音機

如何將一個對象(不可觀察)綁定到一個複選框和廣播值,以便我得到的值(值和值)是一個普通對象(無可觀察)。

HTML:

Selection List 
<a class="pull-right" href="#" data-bind="click: addChoice">+</a>   
<table class="selection" data-bind="foreach: Choices"> 
<tr> 
    <td><input type="text" data-bind="value: Id" /></td> 
    <td><input type="text" data-bind="value: Text" /></td> 
</tr> 
</table> 
Checkbox Values: <br /> 
<!-- ko foreach: {data: Choices() } --> 
<input type="checkbox" data-bind="value: ko.toJS($data), checked: $root.Values" /><span data-bind="text: Text" ></span><br /> 
<!-- /ko --> 
Radio Value: <br /> 
<!-- ko foreach: {data: Choices() } --> 
<input type="radio" data-bind="value: ko.toJS($data), checked: $root.Value" /><span data-bind="text: Text" ></span><br /> 
<!-- /ko --> 
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre> 

的Javascript:

function VM() { 
var self = this 
self.Value = ko.observable() 
self.Values = ko.observableArray([]) 

self.Choices = ko.observableArray([]) 
self.Choice = function (id, text) { 
    this.Id = ko.observable(id) 
    this.Text = ko.observable(text) 
} 
self.addChoice = function() { self.Choices.push(new self.Choice("C" + (self.Choices().length + 1), "Text Here")) } 
} 
var vm = new VM() 
ko.applyBindings(vm) 

回答

2

看到這個答案(https://stackoverflow.com/a/14863924/1287183)自定義綁定,提供你想要的複選框。這裏有一個假設值是$data一個簡單的版本:即工作方式類似於單選按鈕

<input type="checkbox" data-bind="checkedInArray: $root.Values" /> 

這裏有一個結合:

ko.bindingHandlers.checkedInArray = { 
    init: function (element, valueAccessor, all, vm, bindingContext) { 
     ko.utils.registerEventHandler(element, "click", function() { 
      var array = valueAccessor(), // don't unwrap array because we want to update the observable array itself 
       value = bindingContext.$data, 
       checked = element.checked; 
      ko.utils.addOrRemoveItem(array, value, checked); 
     }); 
    }, 
    update: function (element, valueAccessor, all, vm, bindingContext) { 
     var array = ko.utils.unwrapObservable(valueAccessor()), 
      value = bindingContext.$data; 

     element.checked = ko.utils.arrayIndexOf(array, value) >= 0; 
    } 
}; 

你的HTML將成爲這個

ko.bindingHandlers.checkMe = { 
    init: function (element, valueAccessor, all, vm, bindingContext) { 
     ko.utils.registerEventHandler(element, "click", function() { 
      var checkedValue = valueAccessor(), 
       meValue = bindingContext.$data, 
       checked = element.checked; 
      if (checked && ko.isObservable(checkedValue)) { 
       checkedValue(meValue); 
      } 
     }); 
    }, 
    update: function (element, valueAccessor, all, vm, bindingContext) { 
     var checkedValue = ko.utils.unwrapObservable(valueAccessor()), 
      meValue = bindingContext.$data; 

     element.checked = (checkedValue === meValue); 
    } 
}; 

這裏他們在行動:http://jsfiddle.net/mbest/kf6U8/3/