简体   繁体   English

在敲除中的foreach / descantant绑定中了解根模型中可观察的位置

[英]Knowing where observable lives in root model in foreach/descendant bindings in knockout

This is a really niche scenario where ideally I need to be able to have a binding on a property, but be able to know where that property lives within the root view model. 这是一个真正的利基场景,理想情况下,我需要能够对属性进行绑定,但是必须知道该属性在根视图模型中的位置。

So for example lets say I have the object: 例如,假设我有一个对象:

{
   id: ko.observable(1),
   name: ko.observable("some user"),
   groups: [
      { id: ko.observable(1), name: ko.observable("some group") },
      { id: ko.observable(2), name: ko.observable("some group") },
   ]
}

Now the problem here is if i were to have bindings like this: 现在的问题是,如果我要像这样绑定:

<div>
<!-- ko foreach: groups -->
    <input data-bind="value: name, custom-binding: { property: name, other: foo }" />
<!-- /ko -->
</div>

Now I need to be able to resolve name here to rootModel.groups[currentIndex].name opposed to just name . 现在,我需要能够将此处的name解析为rootModel.groups[currentIndex].name而不仅仅是name Currently I don't think there is a way to know in the binding that the property is "name" as it just sees the value, so I may need to pass this in as a string, or have a custom attribute on the object that the binding looks for. 目前,我认为在绑定中没有一种方法可以知道该属性是"name"因为它只是看到值,因此我可能需要将其作为字符串传递,或者在该对象上具有自定义属性绑定寻找。 Either way I need to be able to somehow get the property path for each observable (in related to the rootModel applied in its scope) within the scope of the binding. 无论哪种方式,我都需要能够以某种方式获取绑定范围内每个可观察到的属性路径(与在其范围内应用的rootModel有关)。

I know it seems crazy, and it is but it is still something I need to be able to do if at all possible. 我知道这似乎很疯狂,但这确实是我需要做的,如果有可能的话。 So foreach is just one scenario where the child binding scope changes and is wrapped so for all scenarios I need to be able to build a property-path for properties which are used with this custom binding. 因此,foreach只是其中一个子绑定范围发生变化并被包装的场景,因此对于所有场景,我都需要能够为与该自定义绑定一起使用的property-path建立一个property-path

So is there a way to do this? 那么有没有办法做到这一点?

There seemed to be no easy way to do this, so I had to write pre-processors for certain bindings to cache the scope and then apply that as a new binding at runtime (as pre processors cannot access binding context). 似乎没有简单的方法来执行此操作,因此我不得不为某些绑定编写预处理器以缓存作用域,然后在运行时将其作为新绑定应用(因为预处理器无法访问绑定上下文)。

Then in the actual bindings they are proxied and they lookup if there is any parent with an existing scope, then the local property is appended and cached for child lookups on the binding context. 然后,在实际绑定中将它们代理,并查找是否存在任何具有现有作用域的父对象,然后在绑定上下文上附加并缓存local属性以进行子查找。

This is being used in: 这被用于:

https://github.com/grofit/treacherous https://github.com/grofit/treacherous

So feel free to look at how its done there and if there is a better solution please let me know :) 因此,请随时查看它的完成情况,如果有更好的解决方案,请告诉我:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM