​返回目录​

对于下拉列表框的绑定在之前的knockoutjs文章中已经介绍过,今天主要说一下级联的select,事实上,在knockoutjs里,是以数据绑定为中心的,而数据是以面向对象为前提的,而对于级联绑定来说,它也是一种面向对象里关系对象的体现,有了关系对象,我们就可以把级联很容易的开发出来,而不用像之前JS那么麻烦了。

准备数据对象

var Grade_Subject_R = function () {
var self = this;
self.Grades = [
{

'subjects': [{ 'id': '1', 'name': '语文' },
{ 'id': '2', 'name': '数学' },
{ 'id': '3', 'name': '英语' }],
'arid': '1',
'name': '小学'
},
{

'subjects': [{ 'id': '1', 'name': '语文' },
{ 'id': '2', 'name': '数学' },
{ 'id': '3', 'name': '英语' },
{ 'id': '4', 'name': '物理' },
{ 'id': '22', 'name': '化学' },
{ 'id': '23', 'name': '生物' }],
'arid': '2',
'name': '初中'
},
{
'subjects': [{ 'id': '1', 'name': '语文' },
{ 'id': '2', 'name': '数学' },
{ 'id': '3', 'name': '英语' },
{ 'id': '4', 'name': '物理' },
{ 'id': '22', 'name': '化学' },
{ 'id': '23', 'name': '生物' },
{ 'id': '24', 'name': '历史' }],
'arid': '3',
'name': '高中'
}
];


self.grade = ko.observable();
self.subject = ko.observable();

/*
当前选中的年级ID为self.grade().id
当前选中的学科ID为self.subject().id

HTML代码:
<select data-bind="
options: Grades,
optionsText: 'name',
value:grade,
optionsCaption: '选择年级'">
    </select>
    <span data-bind="with:grade">
     <select data-bind="
     visible: $parent.grade,
     options: Subjects,
     optionsText: 'name',
     value:$parent.subject,
     optionsCaption: '选择学科'">
     </select>
     </span>

<span data-bind="with:grade">
<!-- ko foreach: Subjects -->
<input type="checkbox" data-bind="value: id, checked: $root.subject" />
<span data-bind="text: name"></span>
<!-- /ko -->
</span>


*/


}

JS代码

var model = new Grade_Subject_R();
ko.applyBindings(model);

for (var i in model.Grades) {
if (model.Grades[i].arid == "2") {
model.grade(model.Grades[i]);
break;
}
}

 

HTML代码

<select data-bind="  
options: Grades,
optionsText: 'name',
value:grade,
optionsCaption: '选择年级'">
</select>
<!-- ko with:grade -->
<select data-bind="
visible:$parent.grade,
options: subjects,
optionsText: 'name',
value:$parent.subject,
optionsCaption: '选择学科'">
</select>
<!-- /ko -->

效果截图

MVVM架构~knockoutjs系列之级联select_面向对象

MVVM架构~knockoutjs系列之级联select_数据_02

​返回目录​

 

作者:仓储大叔,张占岭,
荣誉:微软MVP