我修复了你的代码。有很多无用的代码。所以如果我删除太多请告诉我。
这是视图:
<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);"
}];
}
见小提琴
我希望它有所帮助。