简体   繁体   中英

Knockout binding with Durandal

I am using durandal to create a web application. I am using knockout to bind values to page from server. I have an issue in binding knockout observableArray to page and it is a bit complex array.

My observableArray looks like,

在此处输入图片说明

In view,

        <ul data-bind="foreach: products">
            <li><span data-bind='text: product' /></li>
        </ul>

No error and not working.

js code.

    define(['plugins/http', 'durandal/app', 'knockout'], function (http, app, ko) {
        var system = require('durandal/system');
        var vm = {
            activate: activate,
            attached: viewAttached,
            products: ko.observableArray([])
        };
        return vm;

        function activate() {       
            var that = this;
            var pdts;
            var recs;
            var recipeJson = [];
            http.get('http://***/Umbraco/Api/Products/GetAllProducts').then(function (response) {
                pdts = response;
                http.get('http://***/Umbraco/Api/Recipes/GetAllRecipes').then(function (response1) {
                    recs = response1;
                    $.each(pdts, function (i, item) {
                        var json = [];
                        $.each(recs, function (j, jtem) {
                            if (item.DocumentTypeId == jtem.BelongstoProduct) {                           
                                json.push(jtem);                            
                            }
                        });

                        jsonitem = {}
                        jsonitem["product"] = item.ProductName;
                        jsonitem["recipes"] = json;
                        recipeJson.push(jsonitem);

                    });
                    that.products = recipeJson;
                    return that.products;
                });
            });                                                           
        }

        function viewAttached(view) {
            $("#accordion > li > div").click(function () {
                if (false == $(this).next().is(':visible')) {
                    $('#accordion ul').slideUp(300);
                }
                $(this).next().slideToggle(300);
            });
        }
    });

Please help, Thanks.

When you write

that.products = recipeJson;

you're replacing your observableArray with a plain array. You should either write

that.products(recipeJson);

instead, or just push each item directly into the observable array instead of going through recipeJson at all, with that.products.push(jsonItem) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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