我正在尝试创建一个简单的 isDirty
样式的 Knockout 绑定(bind)。我看过使用 toJS
转换的示例,但使用这种方法多次触发可观察对象会变得有点复杂。据我所知,我想预先订阅 observable,我想我应该这样做。这是我目前获得的代码:
var isDirty = false;
this.types = ko.observableArray([]);
this.instances = ko.observableArray([]);
this.selection = ko.observable();
this.filters = ko.observableArray([]);
// Some Logging to try and figure out what's going on
this.types.subscribe(function() { console.log("types changed " + new Date().getTime()) });
this.instances.subscribe(function() { console.log("instances changed " + new Date().getTime()) });
this.selection.subscribe(function() { console.log("selection changed " + new Date().getTime()) });
this.filters.subscribe(function() { console.log("filters changed " + new Date().getTime()) });
// Flag to use to determine if the context property has changed
this.isDirty = ko.computed(function() {
console.log("isDirty changed " + new Date().getTime());
let types = self.types();
let instances = self.instances();
let selection = self.selection();
let filters = self.filters();
return isDirty = !isDirty;
}).extend({ rateLimit: 500 });
this.isDirty.subscribe(function(changes) {
console.log("context changed " + new Date().getTime());
});
所以我的代码可能会在任何时候修改types
、instances
、selection
或filters
而我不真想太在意这个了。实际上,会有几个快速连续的修改(例如,一个新项目被添加到 types
并且同时修改了 selection
)。
我遇到的问题是,即使使用了我尝试添加的 rateLimit
,我似乎也多次触发,但我不明白为什么。这是我进行更改时的控制台输出:
context.js:59 isDirty changed 1455203776330
context.js:52 types changed 1455203776331
context.js:53 instances changed 1455203776333
context.js:54 selection changed 1455203776333
context.js:55 filters changed 1455203776333
context.js:52 types changed 1455203776334
context.js:53 instances changed 1455203776334
context.js:54 selection changed 1455203776335
context.js:52 types changed 1455203776409
context.js:53 instances changed 1455203776413
context.js:54 selection changed 1455203776413
context.js:59 isDirty changed 1455203776832
context.js:68 context changed 1455203776832
context.js:59 isDirty changed 1455203776912
context.js:68 context changed 1455203776913
所以我无法弄清楚为什么在进行了所有更改之后(例如 1455203776413
处的 selection
更改是最后一次更改)为什么 isDirty
之后会触发两次...
我要补充一点,我正在尝试整理一个片段来重现此错误,尽管目前这似乎不起作用。我只是想弄清楚我的代码的哪些其他部分可能对此产生副作用。
最佳答案
这里有一个教训 - 确保您只跟踪一个项目。碰巧有 ViewModel
的副本 正在传递,这也触发了控制台。
关于javascript - 速率限制计算触发两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35343186/