1
votes

I am using knockout foreach binding to bind a div. But when i click the button a new model does not get created and model keep expanding continously.I want my data should be binded only once not again and again.What wrong i am doing. Here is Here is a demo of problem

function bindValues() {

            var obj1 = { Name: ko.observable("location & size") };
            var obj2 = { Name: ko.observable("font") };
            var obj3 = { Name: ko.observable("border lines + fills") };
            var obj4 = { Name: ko.observable("alignment + padding") };

            var model = new Object({
                Styles: ko.observableArray()

            });

            model.Styles.push(obj1);
            model.Styles.push(obj2);
            model.Styles.push(obj3);
            model.Styles.push(obj4);

            ko.applyBindings(model, document.getElementById("style-accordion"));

  }
2

2 Answers

2
votes

its because you push the value again and again to your observableArray and you call applyBindings everytime, you only need to apply the bindings once and overwrite the array

        var model = new Object({
            Styles: ko.observableArray()

        });
        ko.applyBindings(model, document.getElementById("style-accordion"));


    function bindValues() {

        var obj1 = { Name: ko.observable("location & size") };
        var obj2 = { Name: ko.observable("font") };
        var obj3 = { Name: ko.observable("border lines + fills") };
        var obj4 = { Name: ko.observable("alignment + padding") };

        // override instead of push
        model.Styles([obj1,obj2,obj3,obj4]);


    }

fiddle

2
votes

Because you're calling ko.applyBindings every time bindValues is called. This function should only be called once in your case.

I'd recommend moving bindValues inside your ViewModel like this:

var model = {
    Styles: ko.observableArray(),
    bindValues: function() {

        var obj1 = { Name: ko.observable("location & size") };
        var obj2 = { Name: ko.observable("font") };
        var obj3 = { Name: ko.observable("border lines + fills") };
        var obj4 = { Name: ko.observable("alignment + padding") };


        model.Styles.push(obj1);
        model.Styles.push(obj2);
        model.Styles.push(obj3);
        model.Styles.push(obj4);
    }

};
ko.applyBindings(model);

See http://jsfiddle.net/tjjc5bcq/