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

时间:2012-07-17 17:55:24

标签: javascript knockout.js

我在项目中将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>

1 个答案:

答案 0 :(得分:1)

由于删除了jquery.tmpl,我将其添加为答案。但是为了增加价值,这里是你的viewModel,其中remove函数被移动到viewmodel中(并在a fiddle中)

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>