选择带有敲除绑定的更改事件,我怎么知道它是否是真正的更改 [英] change event on select with knockout binding, how can i know if its a real change
问题描述
我正在构建一个权限UI,我有一个权限列表,每个权限旁边都有一个选择列表.权限由绑定到选择列表的可观察对象数组表示:
<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>
现在的问题是这样的:当UI首次填充时,将引发change事件.我调用ajax函数,获取权限列表,然后为每个权限项引发事件.这真的不是我想要的行为.我希望仅当用户真正在选择列表中为权限选择新值时才提高它,
实际上您要查找事件是由用户还是由程序触发的,很明显,该事件将在初始化时触发. /p>
添加subscription
的删除方法在所有情况下都无济于事,原因是因为在大多数模型中都将像这样实现
- 使用未定义的数据初始化模型,只需构建
(actual KO initilization)
- 使用初始数据
(logical init like load JSON , get data etc)
更新模型
- 用户互动和更新
我们要捕获的实际步骤是在3中进行更改,但是在第二步中,subscription
将获得call,
因此,更好的方法是添加事件更改,例如
<select data-bind="value: level, event:{ change: $parent.permissionChanged}">
并在permissionChanged
函数
this.permissionChanged = function (obj, event) {
if (event.originalEvent) { //user changed
} else { // program changed
}
}
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屋!