【发布时间】:2015-11-23 17:12:40
【问题描述】:
我想在页面上显示项目列表,并能够通过使用所有位置的下拉列表来动态重新定位项目。从下拉列表中选择一个位置将更改项目的当前位置并重新移动列表中任何受影响元素的位置。
我确实有这个概念的工作版本,但并不理想。出于某种原因,当我引用我的 selectedItems 计算数组时(我通过设置 selectedItem 可观察项来过滤我的项目),返回项目中包含的位置是项目的原始位置值,而不是通过设置的位置值下拉菜单/我的重新定位功能。这有点奇怪,因为 'items' observableArray 确实包含更新后的值,并且 computedArray 确实返回了正确的项目,只是没有最新的值。
下面是一个工作的 JSfiddle。但是,它进行了大量的手动计算,并且没有利用如上所述的计算数组。该问题可能与从 ViewModel 外部设置 Knockout observables 有关。要查看问题,请取消注释“文档就绪”块中的 2 行,我尝试在其中查找项目的当前位置,并注释掉我手动查找当前项目的 for 循环。
https://jsfiddle.net/tq1m873m/5/
一般来说,我是 KnockoutJS 和 JS 的新手,请保持温和 :)
$(document).ready(function () {
$("select[id^='selectName_']").change(function () {
//Extract the item ID from the select html id attribute
var curItemIDNum = $(this).attr('id').substring(15);
var currentPos = 0;
// myViewModel.selectedItem("item" + curItemIDNum);
// currentPos = myViewModel.selectedItems()[0].position();
// START - really bad code, shield your eyes
// I can't seem to get the current position via the 2 commented lines above and have to resort to converting the observable array to a regular array and pulling the value that way. Not pretty!
var itemsJS = ko.toJS(self.items());
for (var x = 0; x < itemsJS.length; x++) {
if (("item" + curItemIDNum) == itemsJS[x].name) {
currentPos = itemsJS[x].position;
break;
}
}
// END - really bad code
reposition("item" + curItemIDNum, currentPos, $(this).val());
refreshDropDowns();
});
refreshDropDowns();
});
【问题讨论】:
标签: javascript jquery knockout.js