ko-striveneditor.js (3096B)
1 import StrivenEditor from './striveneditor'; 2 3 export default class KoStrivenEditor { 4 constructor(ko, bindingName = 'striveneditor', defaultOptions = {}) { 5 if (!ko.bindingHandlers.striveneditor) { 6 ko.bindingHandlers.striveneditor = { 7 init: function (element, valueAccessor, allBindings, viewModel, bindingContext) { 8 // Get options 9 let options = valueAccessor(); 10 // Options must be passed as an observable 11 if (!ko.isObservable(options)) { 12 throw 'Options must be an observable.'; 13 } 14 15 // Get the value binding in case we are binding the editor's contents to an observable 16 let value = allBindings().value; 17 if (value && !ko.isObservable(value)) { 18 throw 'Value must be an observable.'; 19 } 20 21 // Pass the value to the editor in options 22 options().value = value(); 23 24 let onChange = null; 25 let changeOpt = options().change; 26 if (changeOpt) { 27 if (ko.isObservable(changeOpt)) { 28 onChange = (val) => changeOpt(val); 29 } else { 30 onChange = changeOpt; 31 } 32 } 33 34 const config = { 35 ...defaultOptions, 36 ...options(), 37 change: onChange, 38 toolbarTemplate: options().toolbarTemplate && options().toolbarTemplate() 39 } 40 let editor = new StrivenEditor(element, config ); 41 let pauseUpdate = false; 42 43 // Handle updates and changes to value observable 44 if (ko.isObservable(value)) { 45 // Listen to input event 46 editor.body.oninput = (e) => { 47 pauseUpdate = true; 48 value(editor.getContent()); 49 setTimeout(function () { 50 pauseUpdate = false; 51 }, 0); 52 }; 53 54 // Subscribe to the value observable to detect when it is changed and update the editor 55 value.subscribe((newValue) => { 56 // Update the content if it's not being updated from within the editor 57 if (!pauseUpdate) { 58 editor.setContent(newValue); 59 } 60 }); 61 } 62 63 // Set the editor in options 64 options().api = editor; 65 66 ko.applyBindings(bindingContext, editor.toolbar); 67 return { controlsDescendantBindings: true }; 68 } 69 }; 70 } 71 } 72 }