【发布时间】:2014-07-29 22:47:36
【问题描述】:
您好,感谢您的关注。
我有一个层次很深的动态调查:
<assessment>
<criterionTypes>
<criterionType>
<criteria>
<criterion>
<responses>
<response>
<assessmentResponses>
<assessmentResponse>
有时,我会让数组中的一些可观察项没有以正确的顺序绑定到表单。
尽管我迭代了该集合,在将其移交给视图之前调整了排序,甚至在 Chrome 调试器中以正确的顺序查看该列表。我能够通过在 foreach 中为那些表现不佳的集合应用一个排序例程来解决这个问题。像这样:
<!-- ko foreach: criterionTypes -->
<div data-bind="foreach: criteria.sort($root.context.sort.criteria),
或
<!-- ko foreach: assessmentResponses.sort(function (l, r) { return (l.id() == r.id()) ? (l.id() > r.id() ? -1 : 1) : (l.id() > r.id() ? -1 : 1) }) ... -->
到目前为止一切顺利。但是,我有一个功能,用户可以添加新行,并且当模型在淘汰赛中更新时,UI 不会反映这些更改。因此,如果我放弃排序,模型绑定会正常工作,并且 UI 会按预期更新。
在我的更新按钮中,我尝试在点击事件中重新绑定:
var addResponse = function (response) {
core.addResponse(assessment(), response);
ko.applyBindings(assessment);
};
但无论我尝试绑定什么对象(评估、响应等),我都会遇到同样的错误
未捕获的错误:无法解析绑定。 消息:ReferenceError:路由器未定义; 绑定值:compose: {model: router.activeItem, afterCompose: router.afterCompose, 过渡:'入口'}
我不确定我该如何处理。也许一个自定义绑定会在 foreach 上执行排序,但我无法解决这个问题(双关语)。
<div id="boolean.secondaryResponse" data-bind="if: isSecondaryResponse(), visible: $parent.showSecondaryResponse()>
<!-- ko foreach: assessmentResponses.sort(function (l, r) { return (l.id() == r.id()) ? (l.id() > r.id() ? -1 : 1) : (l.id() > r.id() ? -1 : 1) }) -->
<!-- ko if: customResponse().template() == 'ingredientSource'-->
<div class="col-md-2 col-lg-2" style="z-index: 10"><select data-bind="value: explanation, options: $root.controls.ingredientOrigins, event: { change: $root.context.selectionChanged }, attr: { class: 'form-control ' + criterionCode() + ' ordinal-' + customResponse().ordinal() } " class="remove"></select> </div>
<!-- /ko -->
<!-- ko if: customResponse().template().startsWith('span')-->
<div data-bind="attr: { class: customResponse().template() + ' col-sm-2 col-md-4' }" style="margin-left: -10px; z-index: 10; height: 69px"><input type="text" data-bind="value: textualResponse, attr: { class: 'form-control auto' + customResponse().name() + ' ordinal-' + customResponse().ordinal(), placeholder: customResponse().placeholder }" class="remove" /></div>
<!--/ko -->
<!-- /ko -->
<!-- /ko -->
</div>
【问题讨论】:
-
您是否考虑过使用 ko.computed 对 viewmodel 中的 observable 数组进行排序并绑定计算的 foreach。过去这对我来说效果很好。
标签: knockout.js