3

在每个步骤中使用 Knockout.js 向导验证的修改版本,我计划有一个类似的分步向导。

在 PaymentModel 视图模型步骤中,它有两个子视图模型(payment1Model 和 payment2Model),显示的子视图模型将依赖于 selectedPaymentOption(选项 1 或选项 2)。

我在 PaymentModel 上使用以下代码在选定的视图模型之间切换

self.selectedPaymentOption.subscribe(function(newValue) {
    if(typeof newValue == "undefined")
        return;

    var found = ko.utils.arrayFirst(self.options(), function (item) {
        return item.name() == newValue;
    }, this);

    self.selectedTemplate(found.template);
    self.selectedModel(found.model());
},self);

我可以在第一次好的时候在模板之间切换,但是当切换回来时,我得到一个空引用错误并且下面的绑定失败。

绑定失败

我怀疑这与设置selectedTemplate之前selectedModel(或反之亦然)有关,并且由于模板使用<div data-bind="template: { name: selectedTemplate, data: selectedModel }"></div>.

有什么方法可以推迟更新,直到 selectedTemplate 和 selectedModel 都被更新,或者有更好的方法来解决这个问题?

我的小提琴在这里,代码如下:

<div data-bind="template: { name: 'currentTmpl', data: currentStep }"></div> 

<button data-bind="click: goPrevious, visible: canGoPrevious">Previous</button>
<button data-bind="click: goNext, visible: canGoNext, enable: modelIsValid">Next</button>

<script id="payment1Tmpl" type="text/html">
    <p>payment option 1</p>
    <input id="details1" type="text" data-bind="value: details1, valueUpdate: 'afterkeydown'" /> 
    <select id="expiresMonth" data-bind="options: expiresMonthOptions, value: expiresMonth" />
    <select id="expiresYear" data-bind="options: expiresYearOptions, value: expiresYear" />        
</script>

<script id="payment2Tmpl" type="text/html">
    <p>payment option 2</p>
    <input id="details2" type="text" data-bind="value: details2, valueUpdate: 'afterkeydown'" /> 
</script>

<script id="currentTmpl" type="text/html">
    <h2 data-bind="text: name"></h2>
    <div data-bind="template: { name: getTemplate, data: model }"></div> 
</script>

<script id="nameTmpl" type="text/html">
    <fieldset>
        <legend>Name</legend>
        <p>
            <label for"FirstName">First Name</label>
            <input id="FirstName" type="text" data-bind="value: firstName, valueUpdate: 'afterkeydown'" />
            <p data-bind="validationMessage: firstName"></p>
        </p>
    </fieldset>
</script>

<script id="paymentTmpl" type="text/html">
    <fieldset>  
        <p>
            <label for"someOtherDetail">Some other detail</label>
            <input id="someOtherDetail" type="text" data-bind="value: someOtherDetail, valueUpdate: 'afterkeydown'" /> 
        </p>
        <p>
        <select data-bind="options: paymentOptions, value: selectedPaymentOption"></select>
        <div data-bind="template: { name: selectedTemplate, data: selectedModel }"></div> 
        </p>
    </fieldset>
</script>

<script id="confirmTmpl" type="text/html">
    <fieldset>
        <legend>Name</legend>
        <b><span data-bind="text:NameModel.firstName"></span></b>
        <br/>
    </fieldset>
    <button data-bind="click: confirm">Confirm</button>
</script>


ko.validation.configure({
    insertMessages: false,
    decorateElement: true,
    errorElementClass: 'error'
});

function TemplatePage(id, name, template, model) {
    var self = this;
    self.id = id;
    self.name = ko.observable(name);
    self.template = template;
    self.model = ko.observable(model);

    self.getTemplate = function () {
        return self.template;
    };
}

function ViewModel() {
    var self = this;

    self.nameModel = ko.observable(new NameModel());
    self.paymentModel = ko.observable(new PaymentModel());

    var confirmModel = {
        NameModel: self.nameModel(),
        PaymentModel: self.paymentModel() 
    };

    self.stepModels = ko.observableArray([
        new TemplatePage(1, "Step1", "nameTmpl", self.nameModel()),
        new TemplatePage(2, "Step2", "paymentTmpl", self.paymentModel()),
        new TemplatePage(3, "Confirmation", "confirmTmpl", confirmModel)
    ]);

    self.currentStep = ko.observable(self.stepModels()[0]);

    self.currentIndex = ko.computed(function () {
        return self.stepModels.indexOf(self.currentStep());
    });

    self.getTemplate = function (data) {
        return self.currentStep().template();
    };

    self.canGoNext = ko.computed(function () {
        return (self.currentIndex() < (self.stepModels().length - 1));
    });

    self.modelIsValid = ko.computed(function () {
        if (typeof(self.currentStep().model().isValid) != "undefined") { 
            return self.currentStep().model().isValid();
        }
        else
            return true;
    });

    self.goNext = function () {
        if (self.currentIndex() < self.stepModels().length - 1) {
            var count = self.currentIndex() + 1;
            console.log(count);
            self.currentStep(self.stepModels()[count]);
        }
    };

    self.canGoPrevious = ko.computed(function () {
        return self.currentIndex() > 0;
    });

    self.goPrevious = function () {
        if (self.currentIndex() > 0) {
            var count = self.currentIndex() - 1;
            console.log(count);
            self.currentStep(self.stepModels()[count]);
        }
    };
}

Payment1Model = function() {
    var self = this;
    self.details1 = ko.observable().extend({
        required: true
    });

    self.expiresMonthOptions = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
    self.expiresYearOptions = ["2013", "2014", "2015", "2016"];

    self.expiresMonth = ko.observable().extend({
        required: true
    });

    self.expiresYear  = ko.observable().extend({
        required: true
    });

    ko.validation.group(self);
}

Payment2Model = function() {
    var self = this;
    self.details2 = ko.observable().extend({
        required: true
    });

    ko.validation.group(self);
}


NameModel = function(model) {
    var self = this;

    //Observables
    self.firstName = ko.observable().extend({
        required: true
    });

    ko.validation.group(self);

    return self;
};

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

    self.payment1Model = ko.observable(new Payment1Model());
    self.payment2Model = ko.observable(new Payment2Model());

    self.someOtherDetail = ko.observable().extend({
        required: true
    });

    self.options = ko.observableArray([
        new TemplatePage(1, "Payment1", "payment1Tmpl", self.payment1Model()),
        new TemplatePage(1, "Payment2", "payment2Tmpl", self.payment2Model()),
    ]);

    var optionNames = [];
    for(var i=0; i<self.options().length; i++)
    {
        optionNames.push(self.options()[i].name);
    }

    self.paymentOptions = optionNames;

    self.selectedPaymentOption = ko.observable(optionNames[0]);
    self.selectedTemplate = ko.observable();
    self.selectedModel = ko.observable();

    self.selectedPaymentOption.subscribe(function(newValue) {
        if(typeof newValue == "undefined")
            return;

        var found = ko.utils.arrayFirst(self.options(), function (item) {
            return item.name() == newValue;
        }, this);

        self.selectedTemplate(found.template);
        self.selectedModel(found.model());
    },self);

    ko.validation.group(self);

    self.isParentAndChildValid = function () {
        if (typeof self.selectedModel() == "undefined")
            return false;
        return self.isValid() && self.selectedModel().isValid();
    };

    return {
        someOtherDetail: self.someOtherDetail,
        selectedPaymentOption: self.selectedPaymentOption,
        paymentOptions: self.paymentOptions,
        selectedTemplate: self.selectedTemplate,
        selectedModel: self.selectedModel,
        isValid: self.isParentAndChildValid
    }
}

ko.applyBindings(new ViewModel());
4

1 回答 1

3

这是工作解决方案。现在它可以正常工作,没有任何错误。您需要做的是停止使用 next 分隔变量:

self.selectedTemplate = ko.observable();
self.selectedModel = ko.observable();

相反,您使用另一个变量来保存选项数组中的选定选项:

 self.selectedTemplate = ko.observable(self.options()[0]);

每次更改付款方式时,都会在选项数组中找到已选择的选项。只需将其放入一个新变量 self.selectedTemplate 中:

var found = ko.utils.arrayFirst(self.options(), function (item) {
    return item.name() == newValue;
}, this);
self.selectedTemplate(found);

相应地更改 HTML:

<div data-bind="template: { name: selectedTemplate().template, data: selectedTemplate().model() }"></div> 

(编辑)用新的 selectedTemplate().template 和 selectedTemplate().model() 更改 selectedTemplate 和 selectedModel 的所有实例

于 2013-07-24T14:28:06.570 回答