【问题标题】:How can I copy an observable in an observableArray to another observableArray?如何将 observableArray 中的 observable 复制到另一个 observableArray?
【发布时间】:2014-06-02 05:27:11
【问题描述】:

我是 JS 和 Knockout 的新手。我想将 observableArray 中的特定 observable 复制到另一个 observableArray。我该怎么做?

HTML

<table>
    <thead>
        <tr>
            <th>Passenger Name</th>
            <th>Meal</th>
            <th>Amount ($)</th>
            <th></th>
        </tr>
    </thead>
    @*render a copy of seats child elements for each entry in the seats array*@
    <tbody data-bind="foreach: seats">
        <tr>
            <td data-bind="text: name"></td>
            @*update the view to make use of the formatted Price*@
            <td>
               <select data-bind="options: $root.availableMeals, 
                                  value: meal, optionsText: 'mealName'">
               </select>
            </td>
            <td data-bind="text: formattedPrice"></td>
            <td><a href="#" data-bind="click: $root.removeSeat">Remove</a></td>
        </tr>
    </tbody>
</table>

要求

【问题讨论】:

  • 你能发布你的视图模型吗?

标签: javascript jquery knockout.js knockout-mapping-plugin


【解决方案1】:

我创建了一个 JS fiddle,它展示了如何使用以下代码在可观察数组之间移动项目:

HTML

<p>first list:</p>
<table>
    <tbody data-bind="foreach: contents">
        <td> <strong>
                 <span id="textKey" data-bind="text: displayKey" />    
            </strong>
        </td>
        <td>
            <input id="textValue" type="text" data-bind="value: displayValue" />
        </td>
        <td>
            <input type="button" data-bind="click: $root.copyItem" value="select" />
        </td>
    </tbody>
</table>

<p>Second list:</p>

<table>
    <tbody data-bind="foreach: selectedContents">
        <td> <strong>
                 <span id="textKey" data-bind="text: displayKey" />    
            </strong>
        </td>
        <td>
            <input id="textValue" type="text" data-bind="value: displayValue" />
        </td>       
    </tbody>
</table>

查看模型:

function ViewModel() {
    var self = this;

    self.contents = ko.observableArray([{
        "displayKey": "Fruit",
            "displayValue": "Bananas"
    }, {
        "displayKey": "Colour",
            "displayValue": "Red"
    }, {
        "displayKey": "Car",
            "displayValue": "Ferrari"
    }]);
    self.selectedContents = ko.observableArray([]);

    self.copyItem = function(item) {
        self.selectedContents.removeAll();
        self.selectedContents.push(item);
    }
}
ko.applyBindings(new ViewModel());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2012-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-30
    相关资源
    最近更新 更多