我已经创建了一个带有knockout observate数组的简单表,在button click上还有一个带有选定项的表。
但是可观察的数组改变并没有绑定html视图。
这是我的代码

<html>
<head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"></script>
    <script type="text/javascript">
    $(function(){
    ViewModel  = function(){
        var self = this;
        self.plant = [
            {name:"plant 1",selected:true},{name:"palnt 2",selected:false},{name:"plant 3",selected:true},{name:"plant 4",selected:false}
        ];
        self.PlantSelected = ko.observableArray([]);
        self.gridSelectedSave  = function(obj){
            console.log(obj);
            this.temp = [];
            self.PlantSelected = ko.observableArray([]);
            if(obj.length > 0){
                for(var i = 0;i<obj.length;i++){
                    if(obj[i].selected){
                       this.temp.push(obj[i]);
                    }
                }
            }

            self.PlantSelected = ko.observableArray(this.temp);
            console.log(self.PlantSelected());
        };
    };
    ko.applyBindings(new ViewModel());
    });
    </script>
</head>
<body>
    <table>
   <tbody data-bind="foreach: plant">
                            <tr>
                                <td>
                                    <span data-bind="text: name"></span>
                                </td>
                            </tr>
                        </tbody>
    </table>
    <hr/>
    <table>
   <tbody data-bind="foreach: PlantSelected">
                            <tr>
                                <td>
                                    <span data-bind="text: name"></span>
                                </td>
                            </tr>
                        </tbody>
    </table>
    <br/><hr/>
    <div data-bind="click: function(){
         $root.gridSelectedSave(plant);
    }">click to show selected</div>
</body>

http://jsfiddle.net/63ygsd52/
我花了一天时间来修理,但没有工作,请记住,这是一个新手淘汰js。非常感谢你的回答。

最佳答案

不能简单地覆盖PlantSelected变量,需要保留原始引用。因此,您需要self.PlantSelected = ko.observableArray([]);而不是self.PlantSelected.removeAll(),然后直接将“选定”项推入其中:self.PlantSelected.push(obj[i]);

self.gridSelectedSave  = function(obj){
    self.PlantSelected.removeAll()
    if(obj.length > 0){
        for(var i = 0;i<obj.length;i++){
            if(obj[i].selected){
               self.PlantSelected.push(obj[i]);
            }
        }
    }
};

http://jsfiddle.net/1no4oumf/

09-25 20:05