KnockoutJS - 将计算值添加到可观察数组

发布于 2025-01-07 23:57:48 字数 660 浏览 4 评论 0原文

我使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

最偏执的依靠 2025-01-14 23:57:48

我一直在解决非常类似的问题,我发现您可以拦截 Broker 对象的创建并使用映射选项参数插入您自己的字段:

var data = { "Brokers":[{"BrokerNum": "2"},{"BrokerNum": "10"}] };

var mappingOptions = {
    'Brokers': {
        create: function(options) {
            return (new (function() {
                this.Url = ko.computed(function() {
                    return 'http://BASEURLHERE/' + this.BrokerNum();
                }, this);

                ko.mapping.fromJS(options.data, {}, this); // continue the std mapping
            })());
        }
    }
};

viewModel = ko.mapping.fromJS(data, mappingOptions);

ko.applyBindings(viewModel);

这是一个演示这一点的小提琴: 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:

var data = { "Brokers":[{"BrokerNum": "2"},{"BrokerNum": "10"}] };

var mappingOptions = {
    'Brokers': {
        create: function(options) {
            return (new (function() {
                this.Url = ko.computed(function() {
                    return 'http://BASEURLHERE/' + this.BrokerNum();
                }, this);

                ko.mapping.fromJS(options.data, {}, this); // continue the std mapping
            })());
        }
    }
};

viewModel = ko.mapping.fromJS(data, mappingOptions);

ko.applyBindings(viewModel);

Here is a fiddle to demonstrate this: http://jsfiddle.net/pwiles/ZP2pg/

一梦浮鱼 2025-01-14 23:57:48

好吧,如果您希望每个代理中都有 Url,则必须将其添加到每个代理中:

$.each(viewModel.Brokers(), function(index, broker){
    broker.Url = ko.computed(function(){return 'BASEURLHERE/' + broker.BrokerNum();});
});

我猜 BrokerNum 不会改变,所以您不妨只计算一次 Url:

$.each(viewModel.Brokers(), function(index, broker){
    broker.Url = 'BASEURLHERE/' + broker.BrokerNum();
});

您还可以通过提供“create”在映射期间添加 Url 属性" 回调 ko.mapping.fromJS 函数。有关详细信息,请参阅映射插件文档

如果只需要 url 绑定到 href,只需绑定 html 中的表达式(在 foreach 绑定内):

<a data-bind="attr: {href: 'BASEURLHERE/' + BrokerNum()}">link to broker details</a>

Well, if you want Url in each broker, you have to add it to each broker:

$.each(viewModel.Brokers(), function(index, broker){
    broker.Url = ko.computed(function(){return 'BASEURLHERE/' + broker.BrokerNum();});
});

I guess BrokerNum is not going to change, so you might as well just calculate Url once:

$.each(viewModel.Brokers(), function(index, broker){
    broker.Url = 'BASEURLHERE/' + broker.BrokerNum();
});

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):

<a data-bind="attr: {href: 'BASEURLHERE/' + BrokerNum()}">link to broker details</a>
度的依靠╰つ 2025-01-14 23:57:48

感谢 Peter Wiles 我有非常相似的解决方案:

var ViewModel = function (data, ranges) {
    var self = this;

    this.productList = ko.observableArray();
    var productListMapping = {
        create: function (options) {
            return (new (function () {
            //this row above i don't understand...
                this.len = ko.computed(function () {
                    //just test function returning lenght of object name
                    // and one property of this model
                    return this.name().length + ' ' + self.cons_slider_1();
                }, this);

                ko.mapping.fromJS(options.data, {}, this); // continue the std mapping
            })());
        }
    }

    this.cons_slider_1 = ko.observable(100);

    ko.mapping.fromJS(data, productListMapping, this.productList);
};

一些差异:
我不是映射到 self,而是映射到 this.product。
输入 json 没有像上面示例中的“Brokers”这样的父名称:

var products = [
    { "id": "pp1", "name": "Blue windy" },
    { "id": "pp1", "name": "Blue windy" }];

所以在 ProductMapping 中我只输入“create:”

但是,我不明白的是 create 函数的结构。有人可以解释一下为什么该函数返回具有属性的新函数。就不能以某种方式简化吗?

Thanks to Peter Wiles i have very similar solution:

var ViewModel = function (data, ranges) {
    var self = this;

    this.productList = ko.observableArray();
    var productListMapping = {
        create: function (options) {
            return (new (function () {
            //this row above i don't understand...
                this.len = ko.computed(function () {
                    //just test function returning lenght of object name
                    // and one property of this model
                    return this.name().length + ' ' + self.cons_slider_1();
                }, this);

                ko.mapping.fromJS(options.data, {}, this); // continue the std mapping
            })());
        }
    }

    this.cons_slider_1 = ko.observable(100);

    ko.mapping.fromJS(data, productListMapping, this.productList);
};

Some differences:
I am not mapping to self, but on this.product.
The input json has not parent name like 'Brokers' in above example:

var products = [
    { "id": "pp1", "name": "Blue windy" },
    { "id": "pp1", "name": "Blue windy" }];

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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文