伙计们,
我有一个ViewModel,它将一个单例注入到它的构造函数中。然后在构造函数中,我在单例实例中的属性上创建一个观察者。
在detached()函数中,我处理了观察者订阅。
constructor( singleton: MySingleton, bindingEngine: BindingEngine )
{
this.observer = bindingEngine
.propertyObserver( singleton, 'state' )
.subscribe( ( newValue, oldValue ) => this.onStateChanged( newValue, oldValue ) ) ;
}
// Sample updated with offending code
detatched()
{
// was calling it incorrectly like this - thought TypeScript would have flagged the problem
// this.observer.dispose ;
// and it should have been like this
this.observer.dispose() ;
// and setting observer to undefined is probably the safest
this.observer = undefined ;
}
发生的事情是每次我导航到页面时都会创建一个ViewModel的新实例,当我离开页面时,会调用detatched。 (我预计会发生)。
但是,观察者不会被删除/处置,并且ViewModel的实例会保留在内存中。当'state'值更改并且onStateChanged被触发时,它会对已创建的所有页面实例进行更新。即我导航到/离开页面的次数。
在记录调试语句时,这一点非常明显。
observer.dispose()不应该删除观察者吗?我的ViewModel实例是否也应该处理?
谢谢
多纳尔
观察者应该只在你的代码中处理,正如你从这个例子中看到的https://codesandbox.io/s/ovvp7m05o5
Click changed called
Click changed called
我认为你不小心覆盖了班级中的观察者引用。在构造函数中创建一次的观察者永远不能再次引用以正确处置。