我尝试使用knockoutjs动态创建选择输入。
我的观点看起来像这样 -
<div data-bind="with: QuestionFilter">
<form>
<div>
<select data-bind="options: categories, optionsText: 'name', optionsValue: 'categoryID', value: selectedCategory">
</select>
</div>
<div data-bind="foreach: details">
<select data-bind="options: subcategories, optionsText: 'name', optionsValue: 'categoryID', value: selectedSubcategory">
</select>
</div>
</form>
</div>
<script type="text/javascript">
ko.applyBindings({
categories = <?php echo json_encode($categories); ?>,
details = ko.observableArray([])
});
</script>
我的JS看起来像这样 -
function QuestionFilter(categories, details) {
var self = this;
self.categories = ko.observableArray(categories);
self.subcategories = ko.observableArray([]);
self.selectedCategory = ko.observable();
self.selectedSubcategory = ko.observable();
self.superSubcategories = ko.observableArray([]);
self.selectedCategory.subscribe(function(category) {
function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].parentCategory_id === nameKey) {
self.subcategories.push(myArray[i]);
}
}
}
search(category, categories);
details.push({ firstName: self.subcategories()});
});
self.selectedSubcategory.subscribe(function(subcategory) {
function subsearch(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].parentCategory_id === nameKey) {
self.superSubcategories.push(myArray[i]);
}
}
}
subsearch(subcategory, categories);
details.push({ firstName: self.superSubcategories()});
});
因此,变量selectedCategory
将按预期执行并触发self.selectedCategory.subscribe
中的函数。变量selectedSubcategory
将无法按预期执行,而是会抛出以下错误 - ReferenceError: selectedSubcategory is not defined
。我认为这与在foreach
绑定中使用with
绑定有关,但我不确定。其他所有工作都按预期工作,我甚至用它来成功地将几个对象添加到details数组中。
需要任何想法或澄清吗?
答案 0 :(得分:0)
看起来我没有在正确的上下文中访问selectedSubcategory。预先$parents[0].
给出了期望的结果。所以它看起来像$parents[0].selectedSubcategory
。奇怪的是,$parents
应该提供与$parents[0]
相同的上下文,但在这种情况下它不起作用......