当我更改 observableArray 时,Knockoutjs 不会更新我的 UI
这是我的模板:
<tr>
<td>
<table>
<thead>
<th>
<span>Option name:</span>
</th>
</thead>
<tbody data-bind="template: {name: 'optionChoiceTemplate', foreach: choices, templateOptions:{choiceArray: choices} }"></tbody>
</table>
<button data-bind="click: function(){choices.push('');}">Add new</button>
</td>
</tr>
但是当我单击“添加新”按钮时,我的视图不会更新以包含带有空字符串的新选项。我已经在调试器中检查了空字符串是否已添加到选项中,并且我已确保选项是一个 observableArray,还有什么可能出错?
This is my template:
<tr>
<td>
<table>
<thead>
<th>
<span>Option name:</span>
</th>
</thead>
<tbody data-bind="template: {name: 'optionChoiceTemplate', foreach: choices, templateOptions:{choiceArray: choices} }"></tbody>
</table>
<button data-bind="click: function(){choices.push('');}">Add new</button>
</td>
</tr>
But when I click the "Add new" button, my view doesn't update to include the new option with the empty string. I've checked in the debugger that the empty string is added to the choices, and I've made sure that choices is an observableArray, what else might be going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是,当将 jQuery 模板插件与
template
绑定和foreach
选项结合使用时,空字符串将被视为 null 值并且不会呈现。您可以通过使用对象
{text: ''}
并绑定text
或通过推送空字符串以外的内容(例如单个空格)来解决此问题。或者,如果您能够迁移到 Knockout 2.0 并使用本机模板,那么您的空字符串项目将正确呈现。
The issue is that when using the jQuery Templates plugin with the
template
binding with theforeach
option, empty strings are treated as null values and are not rendered.You could work around this by using an object
{text: ''}
and binding againsttext
or by pushing something other than an empty string (like a single space).Alternatively, if you are able to move to Knockout 2.0 and use the native templates, then your empty string items will be rendered properly.
我创建了一个小提琴,它使用 HTML 来显示项目列表,并允许用户通过两种方式添加新项目。第一种方法是使用您创建的点击函数。第二种方法是使用点击绑定。
这应该可以回答你的问题。
http://jsfiddle.net/johnpapa/4PfUr/
I created a fiddle that uses your HTML to display a list of items, and allows the user to add a new item in two ways. The first way is using your click function you created. The second way is using a click binding.
This should answer your question.
http://jsfiddle.net/johnpapa/4PfUr/