1

我想实现一种行为:当我从 ComboBox 中选择特定模板时,出现 codemirror textarea 中的代码。请看我的小提琴:http: //jsfiddle.net/GEJsu/1/

    function Template(initialTemplate) {
        var self = this;
        self.name = ko.observable(initialTemplate);
        self.code = ko.computed({
            read: function () {
                return self.name().Code;
            },
            write: function (value) {

            },
            owner: this
        });
    }
4

1 回答 1

0

我修复了你的代码。有很多无用的代码。所以如果我删除太多请告诉我。

这是视图:

<select data-bind="options: availableTemplates,
                   value: selectedTemplate,
                   optionsText: 'Name'"></select>
<br />
<div data-bind="with: selectedTemplate">
    <textarea cols="60" rows="8" style="background: lightblue"
     data-bind="value: Code,
                codemirror: { 'lineNumbers': true, 'mode': 'javascript' }">
     </textarea>
</div>

和视图模型:

// Overall viewmodel for this screen, along with initial state
function ValidationViewModel() {
    var self = this;
    self.selectedTemplate = ko.observable();

    // Non-editable data - would come from the server
    self.availableTemplates = [{
        Name: "Range Validation",
        Code: "var minValue = 'A';\r\nvar maxValue = 'Z';\r\n\r\nreturn (e.value >= minValue && e.value <= maxValue) \r\n   ? true \r\n   : 'this is all wrong!';"
    }, {
        Name: "DateTime",
        Code: "var newDate = new Date(e.value);\r\n\r\nif (newDate != 'Invalid Date')\r\n   return true; \r\n\r\nreturn 'value is not a valid dateTime';"
    }, {
        Name: "Decimal",
        Code: "if (e.value == null || e.value.length == 0)\r\n   return 'please, type something'; \r\n\r\nreturn isFinite(e.value);"
    }];


}

见小提琴

我希望它有所帮助。

于 2013-06-24T20:39:59.167 回答