为Knockoutjs和mapper扩展添加记录功能

时间:2014-05-08 18:44:53

标签: javascript jquery asp.net asp.net-mvc knockout.js

在下面的代码中,我尝试为add / insert添加Option / Prelim行。我期待这个工作,并且在单击“添加选项”按钮时为什么我的视图没有被更新时,我感到很茫然。

  $.postJSON('/Admin/GetPrelimsByJob', { jobId: 109 }, function(data) {
            var length = data.length;
            var insertRecord = {};

            if (length > 0) {
                insertRecord = data[data.length - 1]; //last record is an empty PremlimViewModel for insert

                data.splice(data.length - 1, 1); //remove that blank insert record
            }
            var mapping = {
                create: function(options) {
                    //customize at the root level.  
                    var innerModel = ko.mapping.fromJS(options.data);

                    innerModel.addOption = function() {
                         innerModel.push(ko.mapping.fromJS(insertRecord));
                    };

                    return innerModel;
                }
            }

            viewModel = ko.mapping.fromJS({ prelims: data }, mapping);
            ko.applyBindings(viewModel);

        });

以下HTML:

   <div class="options-body" data-bind="foreach: prelims">
        <div class="options-row-container">
            <div data-bind="attr: { 'data-id': PrelimId }" class="options-row">
                <div class="options-col">
                    <div class="ui-widget">
                        <select class="custom-combox-select" data-bind="foreach: Options, combobox: Option">
                            <!-- ko if: $index() === 0 -->
                            <option value=""></option>
                            <!-- /ko -->
                            <option data-bind="text: OptionLetterText, attr: { value: OptionLetterValue }, attrIf: { selected: 'selected', _if: OptionLetterSelected }"></option>
                        </select>
                    </div>
                </div>

                <div class="options-col text-center">
                    <input type="text" data-bind="value: Qty" />
                </div>
            </div>
        </div>
    </div>
    <button type="button" data-bind="click: prelims.addOption">
        Add Option
    </button>

1 个答案:

答案 0 :(得分:1)

好的,所以我有两件事不正确:

1)我需要声明一个模板:

   <div class="options-body" data-bind="template: { name: 'PrelimsTemplate', foreach: prelims }">

2)我附上了属性名称&#34; prelims&#34;到我的viewModel所以在我的映射中改变了一行:

  var mapping = {
                    create: function (options) {
                        //customize at the root level.  
                        var innerModel = ko.mapping.fromJS(options.data);

                        innerModel.addOption = function () {
                            innerModel.prelims.push(ko.mapping.fromJS(insertRecord));
                        };

                        return innerModel;
                    }
                }