gpt4 book ai didi

javascript - Knockout.js - 如何创建类似于 'with' 的自定义绑定(bind)处理程序

转载 作者:行者123 更新时间:2023-11-30 07:40:49 25 4
gpt4 key购买 nike

我想制作一个自定义绑定(bind)处理程序,类似于 data-bind="withSmartForm: formModel"

但尽管有所有其他功能,我还是希望它表现得像 with,因此当前上下文更改为 formModel,并且我可以访问子属性,如 data-bind="value: email ".

我知道有一些变通方法,比如总是在子属性前加上 formModel 前缀,或者在父元素中放置一个 with: formModel,但是因为我会经常使用这种模式,所以我想保留尽可能短。

在下面的 fiddle 中,我想将 withwithSmartForm 合并到一个 bindingHandler 中。

http://jsfiddle.net/k89Fg/1/

有什么想法吗?谢谢!

更新:工作示例

http://jsfiddle.net/k89Fg/4/ - 感谢 Andrew Walters 的获奖回答!

最佳答案

此处的文档对此进行了描述:http://knockoutjs.com/documentation/custom-bindings-controlling-descendant-bindings.html

来自文档:诸如 with 和 foreach 之类的绑定(bind)在绑定(bind)上下文层次结构中创建了额外的级别。这意味着它们的后代可以通过使用 $parent、$parents、$root 或 $parentContext 访问外部级别的数据。如果您想在自定义绑定(bind)中执行此操作,请使用 bindingContext.createChildContext(someData) 而不是使用 bindingContext.extend()。

例子:

ko.bindingHandlers.withProperties = {
init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// Make a modified binding context, with a extra properties, and apply it to descendant elements
var newProperties = valueAccessor(),
childBindingContext = bindingContext.createChildContext(viewModel);
ko.utils.extend(childBindingContext, newProperties);
ko.applyBindingsToDescendants(childBindingContext, element);

// Also tell KO *not* to bind the descendants itself, otherwise they will be bound twice
return { controlsDescendantBindings: true };
}
};

关于javascript - Knockout.js - 如何创建类似于 'with' 的自定义绑定(bind)处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17630058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com