简体   繁体   English

Knockout.js:在模板中绑定到数组外部的可观察属性

[英]knockoutjs: binding to an observable property outside of an array, in a template

I'm trying to bind part of a template to a property that is on the root of my data model, while building the template off an observable array. 我试图将模板的一部分绑定到数据模型根目录上的属性,同时根据可观察数​​组构建模板。

This jsfiddle: http://jsfiddle.net/mgxyE/2/ illustrates compactly what I'm trying to accomplish. 此jsfiddle: http : //jsfiddle.net/mgxyE/2/紧凑地说明了我要完成的工作。

the span <span data-bind='text: message'></span> is what is failing because I can't figure out how to set up that binding inside a template. span <span data-bind='text: message'></span>失败了,因为我不知道如何在模板中设置该绑定。 Any help? 有什么帮助吗?

If your viewmodel has global scope, then you can simply do: 如果您的视图模型具有全局范围,则只需执行以下操作:

<span data-bind='text: model.message'></span>

In your fiddle, you would want to change the option from onLoad to no wrap (body) for how the JavaScript is loaded. 在您的小提琴中,您希望将选项从onLoad更改为no wrap (body)以了解如何加载JavaScript。

Another options is to pass the value in via templateOptions . 另一个选择是通过templateOptions传递值。 This would look like: 看起来像:

<div data-bind='template: {name :"nodeTemplate", foreach: nodes, templateOptions: { myMessage: message} }'></div>

Then, bind to it like (you could call it message, just used myMessage to show where the name comes from): 然后,像这样绑定它(您可以将其命名为message,只是使用myMessage来显示名称的来源):

<span data-bind='text: $item.myMessage'></span>

Finally, if you use KO 1.3 beta , which I would recommend, then you can simply do: 最后,如果您使用我推荐的KO 1.3 beta ,那么您只需执行以下操作:

<span data-bind='text: $root.message'></span>

With Knockout JS 1.3, you can use the parent binding context: 使用Knockout JS 1.3,您可以使用父绑定上下文:

http://jsfiddle.net/Afx6d/ http://jsfiddle.net/Afx6d/

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

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