我正在尝试编写一个名为divider的自定义绑定。
它简单地将传递的observableArray对象拼接成较小的数组,并用模板包装其元素。它正在工作,但我收到一个错误:
未捕获错误:无法解析绑定。 消息:ReferenceError:未定义列表; 绑定值:foreach:list
这是什么问题?我看不到:)
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);
});