使用淘汰赛绑定更改选择事件,我怎么知道它是否是真正的更改? [英] Change event on select with knockout binding, how can I know if it is a real change?
问题描述
我正在构建一个权限 UI,我有一个权限列表,每个权限旁边都有一个选择列表.权限由绑定到选择列表的可观察对象数组表示:
<div class="permission_row"><span data-bind="text: name"></span><select data-bind="value: level, event:{ change: $parent.permissionChanged}"><option value="0"></option><option value="1">R</option><option value="2">RW</option></选择>
现在的问题是:当 UI 第一次填充时,change 事件会被引发.我调用我的 ajax 函数,获取权限列表,然后为每个权限项引发事件.这真的不是我想要的行为.我希望仅当用户真正为选择列表中的权限选择新值时才提升它,我该怎么做?
其实你想知道事件是由用户触发还是程序触发,很明显,事件会在初始化时触发.
添加subscription
的淘汰方式不会在所有情况下都有帮助,为什么因为在大多数模型中会这样实现
- 用未定义的数据初始化模型,只是结构化
(实际KO初始化)
- 用初始数据更新模型
(逻辑初始化,如加载 JSON、获取数据等)
- 用户互动和更新
我们要捕获的实际步骤是 3 中的更改,但在第二步 subscription
将得到 call ,所以更好的方法是添加像
并在permissionChanged
函数中检测到事件
this.permissionChanged = function (obj, event) {if (event.originalEvent) {//用户改变} else {//程序改变了}}
I am building a permissions UI, I have a list of permissions with a select list next to each permission. The permissions are represented by an observable array of objects which are bound to a select list:
<div data-bind="foreach: permissions">
<div class="permission_row">
<span data-bind="text: name"></span>
<select data-bind="value: level, event:{ change: $parent.permissionChanged}">
<option value="0"></option>
<option value="1">R</option>
<option value="2">RW</option>
</select>
</div>
</div>
Now the problem is this: the change event gets raised when the UI is just populating for the first time. I call my ajax function, get the permissions list and then the event get raised for each of the permission items. This is really not the behavior I want. I want it to be raised only when a user really picks out a new value for the permission in the select list, how can I do that?
Actually you want to find whether the event is triggered by user or program , and its obvious that event will trigger while initialization.
The knockout approach of adding subscription
won't help in all cases, why because in most of the model will be implemented like this
- init the model with undefined data , just structure
(actual KO initilization)
- update the model with initial data
(logical init like load JSON , get data etc)
- User interaction and updates
The actual step that we want to capture is changes in 3, but in second step subscription
will get call ,
So a better way is to add to event change like
<select data-bind="value: level, event:{ change: $parent.permissionChanged}">
and detected the event in permissionChanged
function
this.permissionChanged = function (obj, event) {
if (event.originalEvent) { //user changed
} else { // program changed
}
}
这篇关于使用淘汰赛绑定更改选择事件,我怎么知道它是否是真正的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!