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

问题描述

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

I've written a few custom bindings using KnockoutJS. I'm still unsure when to use ko.util.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);

在这种情况下,他们通过()但是也可以调用 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 。这通常是在自定义绑定中,其中可观察或不可观察的绑定。

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.

在上面的代码中,对<$ c的调用$ c> valueAccessor()实际上并没有展开observable。它只是检索在正确的上下文中传递给绑定的值(它被包装在一个函数中以保护它)。 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 08:42