Search code examples
javascriptknockout.jscodemirror

Integration between Codemirror and Knockout


I want to realize one behavior: when I select specific template from ComboBox appearing code in codemirror textarea. Please, see my fiddle: 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
        });
    }

Solution

  • I fixed your code. There were a lot of useless code. So please let me know if I deleted too much.

    This is the view :

    <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>
    

    And the view model :

    // 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);"
        }];
    
    
    }
    

    See Fiddle

    I hope it helps.