有没有办法在 Knockout JS 中实现主/从类型依赖的可观察量
我的模型中有 2 个具有主/从类型关系的字段。
如果主站更新,从站也应该进行更新。
如果从站更新,主站不受影响。
我已经设法通过手动订阅来实现这一点 - http://jsfiddle.net/ProggerPete/XNUPj/
但我想知道是否可以在不手动绑定的情况下获得相同的结果。我想要它的原因是我不想在销毁视图时取消绑定我的手动订阅。
干杯, 彼得
I've got 2 fields in my model that have a master/slave type relationship.
If the master updates the slave should take the update too.
If the slave updates the master is unaffected.
I've managed to implement this with a manual subscription - http://jsfiddle.net/ProggerPete/XNUPj/
But I'm wondering if I could achieve the same result without the manual binding. The reason I'm wanting it is I'd prefer not to have to unbind my manual subscriptions when i'm destroying my view.
Cheers,
Peter
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,我会说手动订阅是解决您的问题的最直接的方法。
然而,创建您自己的自定义 Observable 非常容易,它封装了此功能并在可写的 dependentObservable 中处理主站和从站的更新。它可能看起来像这样:
你会这样使用它:
customObservable(无论你想怎么称呼它)都会返回一个可写的 dependentObservable,它将更新你可以作为
source
绑定的两个值。本地值也公开为source.local
。因此,您可以在您的场景中使用它,例如: http://jsfiddle.net/rniemeyer/67pDS/
但我不确定您想如何使用此功能。如果您正在寻找接受/取消对可观察对象的编辑的能力,那么您可能需要查看 此自定义可观察值。
显示自定义绑定中的处理的片段:
Generally, I would say that the manual subscription is the most straightforward approach to your question.
However, it is pretty easy to create your own custom observable that encapsulates this functionality and handles updating both the master and slave in a writeable dependentObservable. It might look something like this:
and you would use it like:
The customObservable (call it whatever you want) returns a writeable dependentObservable that will update both values that you can bind against as
source
. The local value is also exposed assource.local
.So, you would use this in your scenario like: http://jsfiddle.net/rniemeyer/67pDS/
I am not sure how you want to use this functionality though. If you are looking for the ability to accept/cancel edits to an observable, then you might want to look at this custom observable.
Snippet to show disposal in custom binding: