Kendo-Knockout:更改bind元素的值时绑定会中断

时间:2012-12-17 11:08:28

标签: knockout.js kendo-ui

我将使用先前提出的问题的代码进行微小的更改,但案例不同:

Kendo-Knockout: Closing window breaks bindings

HTML:

<button onclick="openPopUp()">OpenPopUp</button>

<div id="productionStates" class="hidden">
    <div data-bind="kendoWindow: { isOpen: isOpen, title:'States', center:true, width: 600, height: 150, modal: true, resizable: false, actions: ['Maximize', 'Close'] }" >
        <fieldset>
            <legend>Change state:</legend>
            <table>
                <tr data-bind="foreach: productionStates">
                    <td><button class="k-button" data-bind="value: ProductionState, text: ProductionState" /></td>
                </tr>
            </table>
        </fieldset>
    </div>

</div>

的javascript:

    var ProductionStatesList = function() {
    var self = this;

    ProductionStatesList.prototype.productionStates = 
        ko.observableArray([ { ProductionState: ko.observable("Pending") } ]);

        ProductionStatesList.prototype.openPopUp = function () {
            self.isOpen(true);
        };     

        ProductionStatesList.prototype.isOpen = ko.observable(false);

        ProductionStatesList.prototype.close = function () {
            self.isOpen(false);
        }
};
    var elementIsBound = function (elementId) {
                return !!ko.dataFor(document.getElementById(elementId));
            };


    var myProductionStatesList = ko.observable();
    var openPopUp = function(){
        myProductionStatesList(new ProductionStatesList()); 
        if (!elementIsBound("productionStates")){
            ko.applyBindings(myProductionStatesList, document.getElementById("productionStates"));
        }

        myProductionStatesList().openPopUp(); 
    }

myProductionStatesList是一个可观察的。单击按钮弹出窗口,我将实例化ProductionStatesList视图模型并将其值分配给myProductionStatesList。第一次单击按钮时,每个工作正常。当您关闭弹出窗口并再次单击该按钮时,绑定将被破坏,并且没有任何反应。我希望每次点击按钮都会反弹ProductionStatesList的新实例,因为myProductionStatesList是一个可观察的。我错过了什么?

的jsfiddle:

http://jsfiddle.net/bZF9k/15/

1 个答案:

答案 0 :(得分:2)

我认为在这种情况下你最好的选择就是不需要多次拨打ko.applyBindings

一个不错的选择是创建一个具有observable的视图模型来保存当前的ProductionStatesListopenPopup函数。然后,使用编辑器周围的with绑定。

视图模型可能如下所示:

var viewModel = {
    myProductionStatesList: ko.observable(),
    openPopup: function() {
       var newList = new ProductionStatesList();
       this.myProductionStatesList(newList);
       newList.openPopup();
    }
};

以下是一个示例:http://jsfiddle.net/rniemeyer/wBCdK/