Knockoutjs - 具有绑定和状态

Knockoutjs - With bindings and state

我在组件绑定和状态方面遇到问题。

这是我的 html 模板:

<div class="ts-panel content">
<!--ko with: states.createState-->
<div data-bind="component: 'customer-create'">Testing CreateState</div>
<!--/ko-->
<!--ko with: states.lookupState-->
<div data-bind="component: 'customer-search'">Testing LookupState</div>
<!--/ko-->
</div>

这是我的javascript

var myDataModel = function () {
    var self = this;
    self.states = {};
    self.states.createState = ko.observable(true);
    self.states.lookupState = ko.observable(false);
    self.states.currentState = ko.observable(self.states.createState);
    self.states.changeState = function (state) {
    var currentState = self.states.currentState();
        currentState(false);
        self.states.currentState(state);
        state(true);
    }
};
return myDataModel;

我正在使用另一个脚本通过将点击事件绑定到某些按钮来控制我所处的状态。

我 运行 遇到的问题是,当我更改当前状态时,组件绑定会重置组件的状态。例如。在 customer-create 组件上,我填写了一个表单,然后更改为 lookupState,然后又更改回 createState,表单值消失了。

我认为这是因为组件每次都被清除并重新创建。

我还认为一种解决方案是将所有内容存储在根级别(即存储状态的组件),并在需要时将其全部传递给各个组件。但是,我真的很想将特定于组件的信息保留在这些组件中。

有没有一种方法可以存储组件的状态,或者可以将组件存储在一个变量中并以这种方式绑定到它?

来自documentations

If the expression you supply involves any observable values, the expression will be re-evaluated whenever any of those observables change. The descendant elements will be cleared out, and a new copy of the markup will be added to your document and bound in the context of the new value.

此行为与 if binding as well. You could use the visible 绑定相同。这只是隐藏和显示 div 而没有实际将其从 DOM 中删除。 visible 没有无容器控制流语法。因此,您必须将其添加到 div

<div data-bind="component:'customer-create', visible: states.createState">Testing CreateState</div>