KnockoutJS - 将计算值添加到可观察数组
我使用 KnockoutJS 将数据绑定到页面,ViewModel 由使用 映射插件的 AJAX 调用的 JSON 响应填充,像这样:
$(function () {
$.getJSON("@Url.Action("Get")",
function(allData) {
viewModel = ko.mapping.fromJS(allData);
viewModel.Brokers.Url = ko.computed(function()
{
return 'BASEURLHERE/' + this.BrokerNum();
});
ko.applyBindings(viewModel);
});
});
中间部分不起作用(没有该计算属性它也可以正常工作)。 “Brokers”是一个可观察的数组,我想向数组中的每个元素添加一个计算值,称为 URL。我将该 Brokers 数组绑定到 foreach,并且我想使用该 URL 作为锚点的 href
属性。有什么想法吗?
I'm binding data to a page using KnockoutJS, the ViewModel is being populated by an JSON response from an AJAX call using the mapping plugin, like this:
$(function () {
$.getJSON("@Url.Action("Get")",
function(allData) {
viewModel = ko.mapping.fromJS(allData);
viewModel.Brokers.Url = ko.computed(function()
{
return 'BASEURLHERE/' + this.BrokerNum();
});
ko.applyBindings(viewModel);
});
});
The middle part there doesn't work (it works fine without that computed property). "Brokers" is an observable array, and I want to add a computed value to every element in the array called URL. I'm binding that Brokers array to a foreach, and I'd like to use that URL as the href
attribute of an anchor. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我一直在解决非常类似的问题,我发现您可以拦截 Broker 对象的创建并使用映射选项参数插入您自己的字段:
这是一个演示这一点的小提琴: http://jsfiddle.net/pwiles/ZP2pg/
I've been working through very similar issues and I've found that you can intercept the creation of the Broker objects and insert your own fields using the mapping options parameter:
Here is a fiddle to demonstrate this: http://jsfiddle.net/pwiles/ZP2pg/
好吧,如果您希望每个代理中都有 Url,则必须将其添加到每个代理中:
我猜 BrokerNum 不会改变,所以您不妨只计算一次 Url:
您还可以通过提供“create”在映射期间添加 Url 属性" 回调 ko.mapping.fromJS 函数。有关详细信息,请参阅映射插件文档。
如果只需要 url 绑定到 href,只需绑定 html 中的表达式(在 foreach 绑定内):
Well, if you want Url in each broker, you have to add it to each broker:
I guess BrokerNum is not going to change, so you might as well just calculate Url once:
You can also add Url property during mapping by providing "create" callback to ko.mapping.fromJS function. See mapping plugin docs for details.
If you only need url to bind to href, just bind the expression in html (within foreach binding):
感谢 Peter Wiles 我有非常相似的解决方案:
一些差异:
我不是映射到 self,而是映射到 this.product。
输入 json 没有像上面示例中的“Brokers”这样的父名称:
所以在 ProductMapping 中我只输入“create:”
但是,我不明白的是 create 函数的结构。有人可以解释一下为什么该函数返回具有属性的新函数。就不能以某种方式简化吗?
Thanks to Peter Wiles i have very similar solution:
Some differences:
I am not mapping to self, but on this.product.
The input json has not parent name like 'Brokers' in above example:
So in productMapping i'm typing just 'create:'
But, what i do not understand is the structure of create function. Could somebody explain me why the function returns new function, which has property. Couldn't it be simplified somehow?