0
我正在嘗試編寫一個名爲divider的自定義綁定。獲取'未捕獲的錯誤:無法解析綁定'的錯誤,但代碼工作
它將傳遞的observableArray對象簡單地拼接成更小的數組並將其元素用模板包裹起來。它正在工作,但我得到一個錯誤:
未捕獲的錯誤:無法解析綁定。 消息:ReferenceError:列表未定義; 綁定值:foreach:列表
這裏有什麼問題?我看不出:)
HTML
<form data-bind="divider : { size : 4, list: controls , templateName : 'unit' }" class="form-horizontal"></form>
<script id="unit" type="text/x-jquery-tmpl">
<div class="control-group">
<div class="box" data-bind="template: { name : 'controlTemplate', foreach : $data }"></div>
</div>
</script>
<script id="controlTemplate" type="text/x-jquery-tmpl">
<label data-bind="text:label" class="control-label" />
<div class="controls">
: <input data-bind="value:value" type="text" class="input-small"></input>
</div>
</script>
<script id="dividerTemplate" type="text/x-jquery-tmpl">
<div class="dividerContainer" data-bind="foreach : list ">
<div class="divider" data-bind="template : { name : $parent.name }"></div>
</div>
</script>
JAVASCRIPT
function l(log) {
console.log(log);
}
function Control(label,value) {
var self = this;
this.label = ko.observable(label);
this.value = ko.observable(value);
}
function ViewModel() {
var self = this;
this.controls = ko.observableArray();
for(var i=1;i<=10;i++) {
this.controls.push(new Control('TEST'+i,'VALUE'+i));
}
}
ko.bindingHandlers.divider = {
init: function (element, valueAccessor, allBindingsAccessor, data, context) {
var defaultOptions = { size : 5 };
var options = $.extend(true, defaultOptions, valueAccessor());
var seperatedList = ko.observable([]);
if(options.list().length > 0 && options.templateName !== null) {
var length = options.list().length;
var size = options.size;
var templateName = options.templateName;
for(var i=0; i< (length/size); i++)
seperatedList().push(options.list.slice(i*size, (i+1)*size));
l(ko.toJSON(seperatedList));
ko.applyBindingsToNode( $(element).get(0),
{template: { name: 'dividerTemplate' , data : { list: seperatedList , name : templateName}} }
);
}
}
};
$(document).ready(function(){
var viewModel = new ViewModel();
ko.applyBindings(viewModel);
});