1

我在我的项目中将 knockout.js 从 1.2 升级到 2.1。我正在使用一些基本模板,它们似乎被破坏了。我包括 jQuery.tmpl.js 和 knockout-2.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>
4

1 回答 1

1

由于删除 jquery.tmpl 做到了,我将其添加为答案。但是为了增加价值,这里是你的 viewModel 与 remove 功能移动到 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);
    };
};

和新的button绑定:

<button data-bind="click: $parent.removeAddress">Remove</button>
于 2012-07-17T18:46:49.163 回答