我正在进行ajax调用并将数据加载到ko.observablearray([])
调用self.AllMedia;
然后加载数组我正在为每个媒体执行操作。当我正在绑定 ko.applyBindings(self);
时,我收到错误消息:
knockout-3.4.0.js:72 Uncaught TypeError: Unable to process binding "foreach: function (){return AllMedia }"
Message: Unable to process binding "bootstrapSwitchOn: function (){return Exclude }"
Message: valueBinding.value is not a function
HTML:
<div id="draggablePanelList" data-bind="foreach: AllMedia">
<div class="col-sm-3 list-unstyled">
<div class="panel panel-info">
<div class="panel-heading">
<div class="col-sm-4 text-center">
<label @*for="IsDisabled0"*@ class="control-label">Disabled</label>
<input type="checkbox" id="IsDisabled0" data-bind="bootstrapSwitchOn: { value: Exclude, options: {size: 'mini'}}" />
</div>
</div>
</div>
</div>
</div>
视图模型:
self.load = function() {
self.service.getProductDetail(self.Id(), self.populate);
}
self.populate = function(data) {
ko.mapping.fromJS(data, "", self);
self.loadSubProductsandMedia(data.SubProducts);
}
self.loadSubProductsandMedia = function(data) {
self.AllMedia.removeAll();
for (var j = 0; j < data.length; j++) {
for (var a = 0; a < data[j].Media.length; a++) {
self.AllMedia.push(data[j].Media[a]);
}
}
}
ko.applyBindings(self);
ko.bindingHandlers.bootstrapSwitchOn = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var valueBinding = valueAccessor();
var options = {
state: valueBinding.value(),
size: null,
animate: true,
disabled: false,
readonly: false,
indeterminate: false,
inverse: false,
radioAllOff: false,
onColor: 'primary',
offColor: 'default',
onText: 'ON',
offText: 'OFF',
labelText: ' ',
handleWidth: 'auto',
labelWidth: 'auto',
baseClass: 'bootstrap-switch',
wrapperClass: 'wrapper',
onInit: function(event, state) { },
onSwitchChange: function (event, state) { }
};
ko.utils.extend(options, valueBinding.options);
$(element).bootstrapSwitch(options);
$(element).on('switchChange.bootstrapSwitch', function (e, data) {
valueBinding.value(data);
}); // Update the model when changed.
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var vStatus = $(element).bootstrapSwitch('state');
var vmStatus = ko.utils.unwrapObservable(valueAccessor().value);
if (vStatus !== vmStatus) {
$(element).bootstrapSwitch('state', vmStatus);
}
}
};
答案 0 :(得分:0)
从错误消息看,value
上的valueBinding
属性看起来不是函数/可观察的。
var options = {
state: valueBinding.value(),
...
}
{ value: Exclude, options: {size: 'mini'}
正在传递给绑定,因此value
只是对Exclude
可观察数组上推送的对象AllMedia
的引用,即self.AllMedia.push(data[j].Media[a])
}。
如果Exclude
不是函数/可观察对象,那么它应该只被valueBinding.value
访问。如果您不知道它是否是可观察的,您可以使用ko.unwrap(valueBinding.value)
安全地获取该值。
答案 1 :(得分:0)
答案很简单,这是因为我正在做的推动
的 self.AllMedia.push(数据[j]的.Media [A]); 强>
self.AllMedia是一个可观察的数组,Array中的元素需要是使交换机可用的功能。
<强>解决方案:强>
var media = {
Id: ko.observable(data[j].Media[a].Id),
Default: ko.observable(data[j].Media[a].Default)}
然后推送媒体