如果数据存在,Knockout js网格交换输入字段

knockout js grid swap input fields if data exists

本文关键字:网格 交换 输入 字段 js Knockout 数据 存在 如果      更新时间:2023-09-26

我有一个可编辑的网格,在用户使用ajax登录后,我在其中填充数据。

我正在用设备列表和运输信息填充它。在设备列表json中,我有一个布尔值"byod",如果选定的行具有此数据集为"0"的设备,我想将"MAC地址"文本字段与"Ship to"下拉框交换。

小提琴在这里http://jsfiddle.net/QTUqD/15/,代码如下:

<form id="extMngForm">
    <table class="table table-striped table-bordered">
        <thead>
            <tr>
                <th>Extension</th>
                <th>Name</th>
                <th>Email</th>
                <th>Pin</th>
                <th>Device</th>
                <th>MAC Address</th>
                <th>Ship To</th>
                <th style="width: 100px; text-align:right;"></th>
            </tr>
        </thead>
       <tbody data-bind=" template:{name:templateToUse, foreach: pagedList }"></tbody>
    </table>
    <p class="pull-right addExt"><a class="btn btn-primary" data-bind="click: $root.add" href="#" title="edit"><i class="icon-plus"></i> Add Extension</a></p>
    <div class="pagination pull-left" data-bind='visible: pagedList().length > 0'>
        <ul><li data-bind="css: { disabled: pageIndex() === 0 }"><a href="#" data-bind="click: previousPage">Previous</a></li></ul>
        <ul data-bind="foreach: allPages">
            <li data-bind="css: { active: $data.pageNumber === ($root.pageIndex() + 1) }"><a href="#" data-bind="text: $data.pageNumber, click: function() { $root.moveToPage($data.pageNumber-1); }"></a></li>
        </ul>
        <ul><li data-bind="css: { disabled: pageIndex() === maxPageIndex() }"><a href="#" data-bind="click: nextPage">Next</a></li></ul>
    </div>
    <br clear="all" />
    <script id="extItems" type="text/html">
       <tr>
            <td style="width:20px;" data-bind="text: extension"></td>
            <td data-bind="text: name"></td>
            <td data-bind="text: email"></td>
            <td style="width:20px;" data-bind="text: vmpin"></td>
            <td data-bind="text: device.asObject && device.asObject() && device.asObject().name"></td>
            <td data-bind="text: macAddress"></td>
            <td data-bind="text: shipTo"></td>
            <td class="buttons">
                <a class="btn" data-bind="click: $root.edit" href="#" title="edit"><i class="icon-edit"></i></a>
                <a class="btn" data-bind="click: $root.remove" href="#" title="remove"><i class="icon-remove"></i></a>
            </td>
        </tr>
    </script>
    <script id="editExts" type="text/html">
        <tr>
            <td style="width:20px;"><input style="width:65px;min-width: 65px;" data-errorposition="b" class="required" name="extension" data-bind="value: extension" /></td>
            <td><input data-errorposition="b" class="required" name="name" data-bind="value: name" /></td>
            <td><input data-errorposition="b" class="required" name="email" data-bind="value: email" /></td>
            <td style="width:20px;"><input style="width:65px;min-width: 65px;" data-errorposition="b" class="required" name="vmpin" data-bind="value: vmpin" /></td>
            <td>
            <select data-bind="options: $root.devicesForItem($data), optionsText: 'name', optionsValue: 'id', value: device, valueAsObject: 'asObject'"></select>
            </td>
            <td><input name="macAddress" data-bind="value: macAddress" /></td>
            <td><select style="width:100px;" data-bind="options: $root.addressList, optionsText: 'locationName', optionsValue: 'locationName', value: shipTo"></select></td>
            <td class="buttons">
                <a class="btn btn-success" data-bind="click: $root.save" href="#" title="save"><i class="icon-ok"></i></a>
                <a class="btn" data-bind="click: $root.remove" href="#" title="remove"><i class="icon-remove"></i></a>
            </td>
        </tr>
    </script>
</form>

window.ExtListViewModel = new function () {
    var self = this;
    window.viewModel = self;
    self.list = ko.observableArray();
    self.pageSize = ko.observable(10);
    self.pageIndex = ko.observable(0);
    self.selectedItem = ko.observable();
    self.extQty = ko.observable(20);
    self.devices = ko.observableArray([{"id":"gxp2100","name":"Grandstream GXP-2100","qty":"2","byod":"1"}, {"id":"gxp2100","name":"Grandstream GXP-2100 (BYOD)","qty":"1","byod":"0"}, {"id":"pcom331","name":"Polycom 331","qty":"2","byod":"0"}, {"id":"pcom331","name":"Polycom 331 (BYOD)","qty":"1","byod":"1"}]);
    self.addressList = ko.observableArray(['addressList']);
    self.availableDevices = ko.computed(function() {        
        var usedQuantities = {};
        self.list().forEach(function(item) {
            var device = item.device();
            if (device) {
                usedQuantities[device.id] = 1 + (usedQuantities[device.id] || 0);
            }
        });
        return self.devices().filter(function(device) {
            var usedQuantity = usedQuantities[device.id] || 0;
            return device.qty > usedQuantity;
        });
    });
    self.devicesForItem = function(item) {        
        var availableDevices = self.availableDevices();
        return self.devices().filter(function(device) {
            return device === item.device() || availableDevices.indexOf(device) !== -1;
        });
    }
    self.edit = function (item) {
            self.selectedItem(item);
    };
    self.cancel = function () {
        self.selectedItem(null);
    };
    self.add = function () {
            var newItem = new Extension();
            self.list.push(newItem);
            self.selectedItem(newItem);
            self.moveToPage(self.maxPageIndex());
    };
    self.remove = function (item) {
            if (confirm('Are you sure you wish to delete this item?')) {
                    self.list.remove(item);
                    if (self.pageIndex() > self.maxPageIndex()) {
                        self.moveToPage(self.maxPageIndex());
                    }
            }
    };
    self.save = function () {
            self.selectedItem(null);
    };
    self.templateToUse = function (item) {
        return self.selectedItem() === item ? 'editExts' : 'extItems';
    };
    self.pagedList = ko.dependentObservable(function () {
        var size = self.pageSize();
        var start = self.pageIndex() * size;
        return self.list.slice(start, start + size);
    });
    self.maxPageIndex = ko.dependentObservable(function () {
        return Math.ceil(self.list().length / self.pageSize()) - 1;
    });
    self.previousPage = function () {
        if (self.pageIndex() > 0) {
            self.pageIndex(self.pageIndex() - 1);
        }
    };
    self.nextPage = function () {
        if (self.pageIndex() < self.maxPageIndex()) {
            self.pageIndex(self.pageIndex() + 1);
        }
    };
    self.allPages = ko.dependentObservable(function () {
        var pages = [];
        for (i = 0; i <= self.maxPageIndex() ; i++) {
            pages.push({ pageNumber: (i + 1) });
        }
        return pages;
    });
    self.moveToPage = function (index) {
        self.pageIndex(index);
    };

};
ko.applyBindings(ExtListViewModel, document.getElementById('extMngForm'));
function Extension(extension, name, email, vmpin, device, macAddress, shipTo){
    this.extension = ko.observable(extension);
    this.name = ko.observable(name);
    this.email = ko.observable(email);
    this.vmpin = ko.observable(vmpin);
    this.device = ko.observable(device);
    this.macAddress = ko.observable(macAddress);
    this.shipTo = ko.observable(shipTo);
};
ExtListViewModel.addressList = [{"shipping_address_street":"555 Lane","shipping_address_state":"TX","shipping_address_city":"Dallas","shipping_address_postalcode":"75000","locationName":"Preset"}, {"shipping_address_street":"555 Lane","shipping_address_state":"TX","shipping_address_city":"Dallas","shipping_address_postalcode":"75000","locationName":"Home"}];
//Shows device name not value (knockout extension)
ko.bindingHandlers.valueAsObject = {
    init: function(element, valueAccessor, allBindingsAccessor) {
        var value = allBindingsAccessor().value,
            prop = valueAccessor() || 'asObject';
        //add an "asObject" sub-observable to the observable bound against "value"
        if (ko.isObservable(value) && !value[prop]) {
              value[prop] = ko.observable();
        }
    },
    //whenever the value or options are updated, populated the "asObject" observable
    update: function(element, valueAccessor, allBindingsAccessor) {
        var prop = valueAccessor(),
            all = allBindingsAccessor(),
            options = ko.utils.unwrapObservable(all.options),
            value = all.value,
            key = ko.utils.unwrapObservable(value),
            keyProp = all.optionsValue,
            //loop through the options, find a match based on the current "value"
            match = ko.utils.arrayFirst(options, function(option) {
               return option[keyProp] === key;
            });
        //set the "asObject" observable to our match
        value[prop](match);
    }
};

首先,就像我在你最近的其他帖子中向你展示的那样,如果你想要的值是对象本身,不要使用optionsValue绑定为你的选择(然后你不需要valueAsObject的东西)。所以:

<select data-bind="options: $root.devicesForItem($data), optionsText: 'name', value: device"></select>

第二,你的id需要是唯一的(不像你现在的例子),因为你的代码依赖于它。

然后,剩下的很简单,你只需要在你的扩展对象中计算一个简单的布尔值,它表示是否显示MAC地址或发货的东西,例如:
this.showMac = ko.computed(function() {
        if (self.device())
            return self.device().byod !== '0';
        return true;
});

并在绑定中使用此值,例如<!-- ko if: showMac --><td data-bind="text: showMac() ? macAddress : shipTo>"

小提琴:http://jsfiddle.net/antishok/QTUqD/16/