我升级了Knockout.js,现在我的模板坏了

I upgraded Knockout.js, now my templates are broken

本文关键字:我的 坏了 Knockout js      更新时间:2023-10-21

我在项目中将knockout.js从1.2升级到2.1。我正在使用一些基本的模板,它们似乎已经坏了。我包括jQuery.tmpl.js和knock-out2.1.0.js。希望能得到一个快速的答案。

<ul data-bind="template: {name:'addressesTemplate', foreach:addresses}"></ul>
<button data-bind="click: addAddress">Add Address</button>
<button data-bind="click: save">Save Account</button>
<script id="addressesTemplate" type="text/html">
    <li>
    Address Type: <input data-bind="value: addressType"/><br/>
    Address Line 1: <input data-bind="value: addressLine1"/><br/>
    Address Line 2: <input data-bind="value: addressLine2"/><br/>
    City: <input data-bind="value: city"/><br/>
    State: <input data-bind="value: state"/><br/>
    Country: <input data-bind="value: country"/><br/>
    Zip Code: <input data-bind="value: zipCode"/><br/>
    <button data-bind="click: remove">Remove</button>
    </li>
</script>
<script type="text/javascript">

   function addressModel(id) {
        return {
            id: id,
            addressType: ko.observable(),
            addressLine1: ko.observable(),
            addressLine2: ko.observable(),
            city: ko.observableArray(),
            state: ko.observableArray(),
            country: ko.observableArray(),
            zipCode: ko.observableArray(),
            remove: function () {
                viewModel.addresses.remove(this);
            }
        };
    }
    var viewModel = {
        id : 0,
        username: ko.observable(""),
        addresses: ko.observableArray([]),
        addAddress: function () {
            this.addresses.push(new addressModel(""));
        },

        save: function () {
            alert(ko.toJSON(this));
            $.ajax({
                url: "/account/Save",
                type: "post",
                data: ko.toJSON(this),
                contentType: "application/json",
                success: function(result) {alert(result.message) },
                failure: function(result) { alert('fail') }
            });
        }
    };

    ko.applyBindings(viewModel);
</script>

由于删除了jquery.tmpl,我将添加它作为答案。但为了增加价值,这里是你的viewModel,带有移除功能,向上移动到viewModel(并在小提琴中)中

function addressModel(id) {
    return {
        id: id,
        addressType: ko.observable(),
        addressLine1: ko.observable(),
        addressLine2: ko.observable(),
        city: ko.observableArray(),
        state: ko.observableArray(),
        country: ko.observableArray(),
        zipCode: ko.observableArray()
    };
}
var ViewModel = function() {
    var self = this;
    this.id = 0;
    self.username=  ko.observable("");
    self.addresses= ko.observableArray([]);
    self.addAddress= function() {
        self.addresses.push(new addressModel(""));
    };
    self.removeAddress = function(address) {
        self.addresses.remove(address);
    };
};

和新的CCD_ 1结合:

<button data-bind="click: $parent.removeAddress">Remove</button>