【发布时间】:2017-01-31 20:49:03
【问题描述】:
我使用 subscribe 创建了一个扩展器,目的是拦截用户对输入字段的更改并强制设置一个值。
例如,我在 observable 上设置了“Bar”的强制值。如果用户将其更改为“Foo”,我将强制它为“Bar”并通知用户。 (用于原型/示例解决方案)。
它适用于文本框和单选按钮但不适用于选择框。它似乎在页面加载时触发,而不仅仅是在更改时触发。
小提琴:https://jsfiddle.net/4gus57pd/7/
ko.extenders.forcedValue = function(target, newValue) {
target.subscribe(function(writtenValue) {
console.log(target()+" - "+newValue);
if(newValue != writtenValue){
alert("In this example we will use the value "+newValue+" instead.");
}
target(newValue);
});
return target;
};
this.textbox = ko.observable("Foo").extend({ forcedValue: "Bar" });
this.selectbox = ko.observable(1).extend({ forcedValue: 2 });
当您运行它时,尽管值未更改,但仍会触发选择框扩展器?
【问题讨论】:
-
它对我来说改变得很好。 (FF 51.0.1、Chrome 55.0.2883、IE 11),但是,在页面加载时,尽管弹出警报,所有浏览器中的值都是 1。
-
@Balázs 这就是问题所在,警报是在页面加载时触发的。只有在更改为不同的值时才会弹出。