Codemirror remote autcompletion - codemirror

Codemirror has a nice example for autocompletion : link.
The idea is to have server side autocompletion (e.g. Ajax service that autocompletes Java). Does somebody has an example of a remote autocompletion with codemirror ?

I've been able to get async completions working with CodeMirror 5.3's show-hint.js by using the following (es6 flavoured, so for es3, replace let with var and the => with function)
While there's no actual ajax, it's hopefully obvious how to hook that in, just invoke callback in your ajax calls completion handler.
CodeMirror.registerHelper('hint', 'ajax', (mirror, callback) => {
let words = ['foo', 'bar', 'baz'];
let cur = mirror.getCursor();
let range = mirror.findWordAt(cur);
let fragment = mirror.getRange(range.anchor, range.head);
callback({
list: words.filter(w => w.indexOf(fragment) === 0),
from: range.anchor,
to: range.head
});
});
CodeMirror.hint.ajax.async = true;
CodeMirror.commands.autocomplete = function(mirror) {
mirror.showHint({ hint: CodeMirror.hint.ajax });
};
Key is to set the async property as the docs tells you to:
It is possible to set the async property on a hinting function to
true, in which case it will be called with arguments (cm, callback,
?options), and the completion interface will only be popped up when
the hinting function calls the callback

// javascript code
var editor;
function createEditor (data) {
editor = CodeMirror.fromTextArea(myTextarea, {
mode: "text/x-sql",
extraKeys: {"Ctrl-Q": "autocomplete"},
hint: CodeMirror.hint.sql,
hintOptions: {
tables: data ? data : {}
}
})
}
(function createEditorWithRemoteData () {
$.ajax({
type:'POST',
dataType:'json',
url:'data.json',
success:createEditor,
error:function () {}
})
})();
// data.json
{
"table1": [ "col_A", "col_B", "col_C" ],
"table2": [ "other_columns1", "other_columns2" ]
}

Related

geoJSON onEachFeature Mouse Event

I have a problem where i try to use the onEachFeature Methode for a geoJSON Layer. I try to assign a click listener to every Feature.
The problem is that i always get that error when i click at a feature:
Uncaught TypeError: Cannot read property 'detectChanges' of undefined
I can think of that this is because the Layer is assigned before the constructor runs but to do that in the ngOnInit function wont worked either. Would be cool if ther is a good way to do that :)
constructor(private changeDetector: ChangeDetectorRef){}
fitBounds: LatLngBounds;
geoLayer = geoJSON(statesData, {onEachFeature : this.onEachFeature});
onEachFeature(feature , layer) {
layer.on('click', <LeafletMouseEvent> (e) => {
this.fitBounds = [
[0.712, -74.227],
[0.774, -74.125]
];
this.changeDetector.detectChanges();
});
}
layer: Layer[] = [];
fitBounds: LatLngBounds;
onEachFeature(feature , layer : geoJSON) {
layer.on('click', <LeafletMouseEvent> (e) => {
console.log("tets"+e.target.getBounds().toBBoxString());
this.fitBounds = [
[0.712, -74.227],
[0.774, -74.125]
];
this.changeDetector.detectChanges();
});
}
constructor(private changeDetector: ChangeDetectorRef){}
ngOnInit() {
let geoLayer = geoJSON(statesData, {onEachFeature : this.onEachFeature});
this.layer.push(geoLayer);
}
You need to make sure that the right this is accessible in your callback. You do this using function.bind() in Javascript. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
constructor(private changeDetector: ChangeDetectorRef){}
fitBounds: LatLngBounds;
geoLayer = geoJSON(statesData, {
// Need to bind the proper this context
onEachFeature : this.onEachFeature.bind(this)
});
onEachFeature(feature , layer) {
// 'this' will now refer to your component's context
let that = this;
layer.on('click', <LeafletMouseEvent> (e) => {
that.fitBounds = [
[0.712, -74.227],
[0.774, -74.125]
];
// Aliased 'that' to refer to 'this' so it is in scope
that.changeDetector.detectChanges();
});
}
The let that = this trick is to make sure you don't have the same problem on the click event handler. But, you could also make that handler be a function in your class and use bind to set this.

Unable to call a function when a node is checked/unchecked in JStree

I have a requirement to perform a recursive action whenever a node is checked/unchecked in JStree.
I tried to do the following, but the function is never invoked. How should I call a function from JStree on checking/unchecking a node?
$('#jstree').on("uncheck_node.jstree", function (e, data)
{
subfunction(selectednodetouncheck, data);
};
function subfunction(para1, para2)
{
//some operation;
};
The subfunction is never called.... Please let me know how to call this function.
You should use select_node and deselect_node as below. If you want to check and select a node separately, you need to set the tie_selection param of checkbox plugin in the tree config as false and select/deselect a node manually.
Check demo - Fiddle Demo
$("#jstree")
.jstree({
core: {
data: coredata,
check_callback: true
},
plugins: ["checkbox"],
checkbox: {
tie_selection: false
}
})
.on("select_node.jstree deselect_node.jstree", function(e, data) {
subfunction(data);
})
.on("check_node.jstree uncheck_node.jstree", function(e, data) {
subfunction2(data);
});
function subfunction(data) {
//some operation;
alert('You got me selected: ' + data.node.state.selected)
};
function subfunction2(data) {
//some operation;
alert('You got me checked: ' + data.node.state.checked);
// now you need to decide what you want to select or not
// and do it manually, e.g. like below
var selectFlag = true;
if (selectFlag) {
var action = data.node.state.checked ? 'select_node' : 'deselect_node';
$("#jstree").jstree(action, data.node);
}
};

How do I trigger tinymce 4.x focus and blur events

I realize that this question has been asked and answered several times, but I still can't make many of the solutions work. It seems like most of the discussions are older and maybe not compatible with 4.x.
My goal: be able fire some javascript functions upon focus or blur. Here's the base code:
$('.tiny-mce').tinymce({
script_url : '/xm_js/tinymce4/tinymce.min.js',
});
I tried examples like:
$('.tiny-mce').tinymce({
script_url : '/xm_js/tinymce4/tinymce.min.js',
setup : function(ed) {
ed.onInit.add(function(ed, evt) {
var dom = ed.dom;
var doc = ed.getDoc();
tinymce.dom.Event.add(doc, 'blur', function(e) {
alert('blur!!!');
});
});
}
});
returns:"Uncaught TypeError: Cannot call method 'add' of undefined"
$('.tiny-mce').tinymce({
script_url : '/xm_js/tinymce4/tinymce.min.js',
});
tinymce.activeEditor.on('focus', function(e) {
console.log(e.blurredEditor);
});
returns: "Uncaught TypeError: Cannot call method 'on' of undefined"
(but not sure if I have it in the right place)
$('.tiny-mce').tinymce({
script_url : '/xm_js/tinymce4/tinymce.min.js',
setup: function(editor) {
editor.on('focus', function(e) {
console.log('focus event', e);
});
}
});
returns: "Uncaught SyntaxError: Unexpected identifier"
This works but only when initiating the editor. Other things I've tried but haven't gotten to work:
tinymce.FocusManager
tinymce.activeEditor
What am I missing? Thanks.
UPDATE: found a solution that worked beautifully: Why TinyMCE get focus and blur event, when user jump from other input field?
see the fiddle at http://fiddle.tinymce.com/8Xeaab/1
tinymce.init({
selector: "#editme",
inline: true,
setup: function(editor) {
editor.on('focus', function(e) {
console.log("focus");
});
editor.on('blur', function(e) {
console.log("blur");
});
}
});
Your cuestion title its about TRIGGERING focus and blur events, but you really are asking about HANDLING those events.
If anybody is still looking for triggering the events, the solution should by:
tinymce.init({
selector: "#textarea_123",
...
});
then, to set focus:
var inst = tinyMCE.EditorManager.get('textarea_123');
inst.focus();
I recently ran into this issue and although I am doing this in angularjs I was able to implement a fix for it by creating a directive that registers when you click off of it and then clears the activeElement in the html body. I will add the directive below. You just call it on the object by adding click-off like you would an ng-cloak to a tag.
(function () {
'user strict';
angular.module('app.directives').directive('clickOff', ClickOff);
function ClickOff($parse, $document) {
var directive = {
link: link
};
return directive;
function link(scope, $element, attr) {
var fn = $parse(attr["clickOff"]);
$element.bind('click', function (event) {
event.stopPropagation();
});
angular.element($document[0].body).bind("click", function (event) {
scope.$apply(function () {
$document[0].activeElement.blur();
fn(scope, { $event: event });
});
});
}
}
})();

Select2 with AJAX and Initial Local Data

So I'm trying to get the select2 plugin to work with a Backbone.js / CakePHP app. The idea is that this select2 holds email addresses for contacting people as tasks become completed, but the form is editable. What I want to do is (1) load / display all the already saved email addresses for the task being edited, and (2) I want to still have the select2 perform AJAX searches to list recognized emails.
I keep having this issue where I can either show initial data, OR have the AJAX search feature.
My current code for my select2 box is a Backbone.View, and it looks like:
define([
'backbone',
'jquery',
'jquery.select2'
],
function(Backbone, $, select2) {
var notificationSelector = Backbone.View.extend({
notifications: undefined,
events: {
'change' : 'select2ContactsChanged'
},
initialize: function(attrs) {
this.collection.on('add remove reset', this.render(), this);
this.select2ContactsChanged();
},
render: function() {
var contacts = ["abc#def.com", "joe#banana.com"];
$('.notification-selector').attr('value', contacts);
if(this.select2Control == undefined)
{
// Do Search() + query here
this.select2Control = this.$el.select2({
width: '200px',
placeholder: '#email',
tags: [],
minimumInputLength: 3,
// initSelection: function(element, callback) {
// return $.ajax({
// type: "GET",
// url: "/notifications/fetch/",
// dataType: 'json',
// data: { id: (element.val()) },
// success: function(data) {
// }
// }).done(function(data) {
// console.log(data);
// });
// },
});
}
else
{
// Do Search() + query here
this.select2Control = this.$el.select2({
width: '200px',
placeholder: '#email',
tags: [],
minimumInputLength: 3,
ajax: {
url: '/notifications/search/',
dataType: 'json',
data: function(term, page) {
return {
SearchTerm: term
};
},
results: function(data, page) {
return {
results: data
};
}
}
});
}
},
select2ContactsChanged: function() {
var contacts = this.select2Control.val().split(',');
this.collection.reset(contacts);
}
});
return notificationSelector;
});
I read a response by the creator of Select2 to someone else (https://github.com/ivaynberg/select2/issues/392) in which he says to use a 'custom query' to achieve what seems to be what I want. I'm having trouble finding relevant examples or making enough sense of the docs to figure out what he means.
Can anyone spot what I'm doing wrong / missing?
Thanks for your time!
EDIT
I forgot to mention -- the DOM element this is attached to is <input type="hidden" multiple="true" class="notification-selector select2-result-selectable"></input>
Ok, I finally figured out the solution.
I was misunderstanding $.ajax() -- I did not really think about it actually being an asynchronous call. My code to check for the data being returned from the call was running before the AJAX actually finished, so I was always getting undefined.
I assigned a variable to the AJAX call, and set "async: false", and it worked perfectly.
fetchSetNotifications: function() {
var addresses = $.ajax({
method: 'GET',
dataType: 'json',
context: $('#notifications'),
url: '/Notifications/fetch/',
async: false,
alert(addresses);
}
The jqXHR object I get in 'addresses' then contains the response data I want in the "responseText" attribute.

How to access old and new values before submitting with jeditable

I have a field being updated by jeditable. I want to output a warning message before submitting updates if the value is being reduced (which would result in data being lost), but not if it's being increased.
This seems a good candidate for jeditable's onsubmit function, which I can trigger happily. I can get the new value from $('input', this).val(), but how do I get the original value to which to compare it in this context?
...
Since posting the above explanation / question, I've come up with a solution of sorts. By changing the invokation in jquery.ready from
$('#foo').editable(...);
to
$('#foo').hover(function(){
var old_value = $(this).text();
$(this).editable('ajax.php', {
submitdata {'old_value':old_value}
});
});
I can use settings.submitdata.old_value in the onsubmit method.
But there surely has to be a better way? jeditable must still have the old value tucked away somewhere in order to be able to revert it. So the question becomes how can I access that from the onsubmit function?
Many thanks in advance for any suggestions.
A much easier solution would be to add this line to your submitdata variable
"submitdata": function (value, settings) {
return {
"origValue": this.revert
};
}
Here is my editable (it is using the submitEdit function):
$(function () {
$('.editable').editable(submitEdit, {
indicator: '<img src="content/images/busy.gif">',
tooltip: '#Html.Resource("Strings,edit")',
cancel: '#Html.Resource("Strings,cancel")',
submit: '#Html.Resource("Strings,ok")',
event: 'edit'
});
/* Find and trigger "edit" event on correct Jeditable instance. */
$(".edit_trigger").bind("click", function () {
$(this).parent().prev().trigger("edit");
});
});
In submitEdit origvalue is the original value before the edit
function submitEdit(value, settings) {
var edits = new Object();
var origvalue = this.revert;
var textbox = this;
var result = value;
// sb experiment
var form = $(this).parents('form:first');
// end experiment
edits["field"] = form.find('input[name="field"]').val();
edits["value"] = value;
var returned = $.ajax({
url: '#Url.Action("AjaxUpdate")',
type: "POST",
data: edits,
dataType: "json",
complete: function (xhr, textStatus) {
// sever returned error?
// ajax failed?
if (textStatus != "success") {
$(textbox).html(origvalue);
alert('Request failed');
return;
}
var obj = jQuery.parseJSON(xhr.responseText);
if (obj != null && obj.responseText != null) {
alert(obj.responseText);
$(textbox).html(origvalue);
}
}
});
return (result);
}