遵循有关订阅更改单个实体事件的文档很容易 -
var token;
var myEntity = ko.observable();
if (token == null) {
token = myEntity().entityAspect.propertyChanged.subscribe(function (changeArgs) { trackChanges(changeArgs); });
}
但是,如果我想订阅 observableArray 并跟踪令牌
var tokens = ko.observableArray();
var myEntitys = ko.observableArray();
if (tokens().length === 0) {
ko.utils.arrayForEach(myEntitys(), function (entity) {
var etoken = entity.entityAspect.propertyChanged.subscribe(function (changeArgs) { trackChanges(changeArgs); });
tokens.push(etoken);
});
}
console.log(tokens());
订阅工作正常,但每个令牌都等于相同的值
//This works fine
myEntity().entityAspect.propertyChanged.unsubscribe(token);
//**This does not work because myEntitys does not have an entityAspect, of course **
ko.utils.arrayForEach(tokens(), function (token) {
myEntitys().entityAspect.propertyChanged.unsubscribe(token);
});
//This works, but I am not sure why because token was set above to equal a single entity (myEntity())
ko.utils.arrayForEach(myEntitys(), function (entity) {
entity.entityAspect.propertyChanged.unsubscribe(token);
});
有没有办法在离开视图时取消订阅一切,或者有一种适当的方法来做我上面尝试的事情?如果我再次重新加载相同的视图,它将双重订阅 propertyChange 事件。