本文介绍了什么时候使用 ko.utils.unwrapObservable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用 KnockoutJS 编写了一些自定义绑定.我仍然不确定何时使用 ko.utils.unwrapObservable(item) 查看代码,该调用主要检查 item 是否是可观察的.如果是,则返回 value(),如果不是,则返回值.查看关于创建自定义绑定的 Knockout 部分,它们具有以下语法:

I've written a few custom bindings using KnockoutJS. I'm still unsure when to use ko.utils.unwrapObservable(item) Looking at the code, that call basically checks to see if item is an observable. If it is, return the value(), if it's not, just return the value. Looking at the section on Knockout about creating custom bindings, they have the following syntax:

var value = valueAccessor(), allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);

在这种情况下,它们通过 () 调用 observable,但也调用 ko.utils.unwrapObservable.我只是想弄清楚何时使用一个与另一个,或者我是否应该始终遵循上述模式并同时使用两者.

In this case, they invoke the observable via () but then also call ko.utils.unwrapObservable. I'm just trying to get a handle on when to use one vs. the other or if I should just always follow the above pattern and use both.

推荐答案

你应该使用 ko.utils.unwrapObservable 如果你不知道你是否已经获得了一个 observable.这通常是在自定义绑定中,其中可以绑定可观察或不可观察的对象.

You should use ko.utils.unwrapObservable in cases where you don't know if you have been given an observable or not. This would commonly be in a custom binding where an observable or non-observable could be bound against it.

在您上面的代码中,对 valueAccessor() 的调用实际上并未解开可观察对象.它只是在正确的上下文中检索传递给绑定的值(它被包装在一个函数中以保护它).valueAccessor() 的返回值可能是可观察的,也可能不是.它是传递给绑定的任何内容.

In the code that you have above, the call to valueAccessor() is not actually unwrapping an observable. It is just retrieving the value that was passed to the binding in the correct context (it gets wrapped in a function to protect it). The return value of valueAccessor() may be an observable or not. It is whatever was passed to the binding.

这篇关于什么时候使用 ko.utils.unwrapObservable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 19:43