Knockout 重新绑定注意要点

function ReImport(id) { //点击按钮时调用函数名称,
        var node = document.getElementById('bindingNode'); //bindingNode 为内部绑定订单子项的div或是table id,每次html(data)后会重新建立
        if (node) {
            $(node).unbind();
            $(node).find("*").each(function () {
                $(this).unbind();
            });
            ko.removeNode(node);//解绑 
        }
        //http://localhost:7486/Order/EditByIndex?id=61521
        $("#orderdetalis").html('');
        $.get('@Url.Action("EditByIndex")', { id: id, r: Math.random() }, function (data) { //此处action中包含了<div id="bindingNode">
           
            $("#orderdetalis").html(data); //此处orderdetails为本页面的一个div id 注意,如有错误 jquery html()方法不执行
            $("#myModal").modal();
            var node_new = document.getElementById('bindingNode');  //此处bindingNode因为被remove掉,必须再次查找后 绑定到对像
           
            ko.applyBindings(obj1, node_new);
        })
    }
 function AppViewModel() {
        var self = this;
        self.OrderItems = ko.observableArray([]);
        self.removeOrderItem = function () {
            if (confirm('确认删除吗?')) {
                self.OrderItems.remove(this);
            }
        }
        self.addOrderItem = function () {
            push({ 'ProductName': '', 'ProductCode': '', 'Price': 0, 'Quality': 1 });
        }
        self.TotalAmount = ko.computed(function () {
            var amount = 0;
            var array = self.OrderItems();
            for (var i = 0 ; i < array.length; i++) {
                var price = getFloat(array[i].Price());
                var quality = getFloat(array[i].Quality());
                amount += Math.formatFloat(quality * price, 2);
            }
            return "总金额:" + Math.formatFloat(amount, 2).toString();
        }, this);
    }


    var obj1 = new AppViewModel();

    function push(obj) {
        var itemModel = function (item) {
            var self = this;
            self.ProductName = ko.observable(item.ProductName);
            self.ProductCode = ko.observable(item.ProductCode);
            self.ImportStore = ko.observable(item.ImportStore);
            self.Price = ko.observable(item.Price);
            self.Quality = ko.observable(item.Quality);
        };
        obj1.OrderItems.push(new itemModel(obj));
    }

    function buildArray(array) {
        obj1.OrderItems([]);
        for (var i = 0 ; i < array.length ; i++) {
            push(array[i]);
        }
    }
原文地址:https://www.cnblogs.com/zyug/p/7838109.html