Marvin JS Example - Listen Molecule Import

Back to index

This example describes how to assign an event listener to the sketcher that monitors molecule loading initiated by the user through the UI.

Changing the status of the Listener checkbox switches the listener on or off: When the checkbox is selected, the onMolImport function is assigned to the editor as an event listener of the molImport event. When the checkbox is unselected, the editor unregisters the listener (no more notifications about molecule loading).

The event handler is performed when the molecule is loaded into the editor through the UI. The event handler is triggered by either loading the molecule through the Open dialog or pasting the structure from the clipboard. When the molecule import is performed by the editor API (e.g. calling of the importStructure method), the event handler is not triggered.


		var marvinSketcherInstance;
		$(document).ready(function handleDocumentReady (e) {
			MarvinJSUtil.getEditor("#sketch").then(function (sketcherInstance) {
				marvinSketcherInstance = sketcherInstance;
				initControl();
			},function (error) {
				alert("Cannot retrieve sketcher instance from iframe:"+error);
			});
		});

		function onMolImport(source) {
			var txt = $("#molsource");
			txt.val(""); // delete current content
			txt.val(source);
		}

		function initControl () {
			$("#cbx-listener")[0].checked = false // init initial state of the checkbox
			// assign listener to checkbox
			$("#cbx-listener").change(function() {
				$("#molsource").val("") // clear textarea when listener is (de)activated
				// remove if it has been already set
				marvinSketcherInstance.removeMolImportListener(onMolImport);
				var checked = $("#cbx-listener")[0].checked;
				if(checked) { // setup listener if checkbox is true
					marvinSketcherInstance.addMolImportListener(onMolImport);
				}
			});
		}

	
Back to index