I have set Editors.Text or edit.
{id: "label", name: "name", field: "label",editor: Editors.Text,width: 80},
This enables editing for field on browser.
But how can I catch when editing is finished??
I am checking the event list of slickgrid.
However can't find the appropriate event.
How can I catch the event after editing columns??
It appears that there is no generic event for this - probably not a bad idea to add one. I suspect it is expected that you would write a custom editor and add the event directly to that rather than adding it to the grid.
I assume you want to update some related data or UI when the editing is complete?
[Edit]
The editor has events encapsulated in it for doing this - the grid uses a plugin model with loadValue and applyValue to read/write the data source. I'll post an example of my personal text editor here, as it may help. Note that I have written a data provider for my personal grid to allow it to interface to several custom data objects - this isn't in the standard one you should be using, which is here.
function TextEditor(args) {
var $input;
var defaultValue;
var scope = this;
this.init = function () {
$input = $("<INPUT type=text class='editor-text' />")
.appendTo(args.container)
.on("keydown.nav", function (e) {
if (e.keyCode === $.ui.keyCode.LEFT || e.keyCode === $.ui.keyCode.RIGHT) {
e.stopImmediatePropagation();
}
})
.focus()
.select();
$input.width(args.container.clientWidth); /* mod */
};
this.destroy = function () {
$input.remove();
};
this.focus = function () {
$input.focus();
};
this.getValue = function () {
return $input.val();
};
this.setValue = function (val) {
$input.val(val);
};
this.loadValue = function () {
defaultValue = args.grid.getDataProvider().getValueByColName(args.rowIndex, args.column.field);
defaultValue = defaultValue || "";
$input.val(defaultValue);
$input[0].defaultValue = defaultValue;
$input.select();
};
this.serializeValue = function () {
return $input.val();
};
this.applyValue = function (state) {
args.grid.getDataProvider().setValueByColName(args.rowIndex, args.column.field, state);
};
this.isValueChanged = function () {
return (!($input.val() == "" && defaultValue == null)) && ($input.val() != defaultValue);
};
this.validate = function () {
if (args.column.validator) {
var validationResults = args.column.validator($input.val());
if (!validationResults.valid) {
return validationResults;
}
}
return {
valid: true,
msg: null
};
};
this.init();
}
Related
I've been trying to create an autocomplete dropdown based on the accepted response in this post but the autocomplete dropdown simply isn't showing up. It could be because the response is 9 years old or perhaps I'm doing something wrong. I have tried all of the suggestions that I've come across. Is there an updated way to create this combobox using jquery version 1.12.3, jquery-ui version 1.12.1, and knockoutjs version 3.4.1?
To me is seems like the bindings aren't really taking place because I could rename the custom binding to "jqAuto1" instead of "jqAuto" and there would be no errors, even though "jqAuto1" isn't defined anywhere. Why isn't that being picked up?
Here is my code. Note that the JS script is in a separate, parent solution from the CSHTML and TS files. The browser still finds and executes the JS script.
CSHTML
<input class="form-control form-control-xs" data-bind="value: companyName, jqAuto: { autoFocus: true }, jqAutoSource: myComp, jqAutoValue: mySelectedGuid, jqAutoSourceLabel: 'displayName', jqAutoSourceInputValue: 'coname', jqAutoSourceValue: 'id'" placeholder="Type Company Name and select from list" />
TS
// For list of Companies
class Comp {
_id: KnockoutObservable<string>;
_coname: KnockoutObservable<string>;
_coid: KnockoutObservable<string>;
constructor(id: string, coname: string, coid: string) {
this._id = ko.observable(id);
this._coname = ko.observable(coname);
this._coid = ko.observable(coid);
}
}
myComp: KnockoutObservableArray<Comp>;
mySelectedGuid: KnockoutObservable<string>;
displayName: KnockoutComputed<string>;
...
this.myComp = ko.observableArray([
new Comp("1", "Company 1", "CO1"),
new Comp("2", "Company 2", "CO2"),
new Comp("3", "Company 3", "CO3"),
new Comp("4", "Company 4", "CO4"),
new Comp("5", "Company 5", "CO5")
]);
this.companyName = ko.validatedObservable<string>("");
this.displayName = ko.computed(function () {
return this.myComp.coname + " [" + this.myComp.coid + "]";
}, this);
this.mySelectedGuid = ko.observable("5");
JS
Pretty much what's in the linked post
(function () {
var global = this || (0, eval)('this'),
document = global['document'],
moduleName = 'knockout-binding-jqauto',
dependencies = ['knockout', 'jquery'];
var moduleDance = function (factory) {
// Module systems magic dance.
if (typeof define === "function" && define["amd"]) {
define(moduleName, dependencies.concat('exports'), factory);
} else {
// using explicit <script> tags with no loader
global.CPU = global.CPU || {};
factory(global.ko, global.Globalize);
}
};
var factory = function (ko, $) {
ko.bindingHandlers.jqauto = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var options = valueAccessor() || {},
allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
modelValue = allBindings.jqAutoValue,
source = allBindings.jqAutoSource,
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp,
labelProp = allBindings.jqAutoSourceLabel || valueProp;
//function that is shared by both select and change event handlers
function writeValueToModel(valueToWrite) {
if (ko.isWriteableObservable(modelValue)) {
modelValue(valueToWrite);
} else { //write to non-observable
if (allBindings['_ko_property_writers'] && allBindings['_ko_property_writers']['jqAutoValue'])
allBindings['_ko_property_writers']['jqAutoValue'](valueToWrite);
}
}
//on a selection write the proper value to the model
options.select = function (event, ui) {
writeValueToModel(ui.item ? ui.item.actualValue : null);
};
//on a change, make sure that it is a valid value or clear out the model value
options.change = function (event, ui) {
var currentValue = $(element).val();
alert(currentValue);
var matchingItem = ko.utils.arrayFirst(unwrap(source), function (item) {
return unwrap(inputValueProp ? item[inputValueProp] : item) === currentValue;
});
if (!matchingItem) {
writeValueToModel(null);
}
}
//handle the choices being updated in a DO, to decouple value updates from source (options) updates
var mappedSource = ko.dependentObservable(function () {
mapped = ko.utils.arrayMap(unwrap(source), function (item) {
var result = {};
result.label = labelProp ? unwrap(item[labelProp]) : unwrap(item).toString(); //show in pop-up choices
result.value = inputValueProp ? unwrap(item[inputValueProp]) : unwrap(item).toString(); //show in input box
result.actualValue = valueProp ? unwrap(item[valueProp]) : item; //store in model
return result;
});
return mapped;
}, null, { disposeWhenNodeIsRemoved: element });
//whenever the items that make up the source are updated, make sure that autocomplete knows it
mappedSource.subscribe(function (newValue) {
$(element).autocomplete("option", "source", newValue);
});
options.source = mappedSource();
//initialize autocomplete
$(element).autocomplete(options);
},
update: function (element, valueAccessor, allBindings, viewModel) {
//update value based on a model change
var allBindings = allBindingsAccessor(),
unwrap = ko.utils.unwrapObservable,
modelValue = unwrap(allBindings.jqAutoValue) || '',
valueProp = allBindings.jqAutoSourceValue,
inputValueProp = allBindings.jqAutoSourceInputValue || valueProp;
//if we are writing a different property to the input than we are writing to the model, then locate the object
if (valueProp && inputValueProp !== valueProp) {
var source = unwrap(allBindings.jqAutoSource) || [];
var modelValue = ko.utils.arrayFirst(source, function (item) {
return unwrap(item[valueProp]) === modelValue;
}) || {}; //probably don't need the || {}, but just protect against a bad value
}
//update the element with the value that should be shown in the input
$(element).val(modelValue && inputValueProp !== valueProp ? unwrap(modelValue[inputValueProp]) : modelValue.toString());
}
}
};
moduleDance(factory);
})();
I have not fully understood your question. But knockout is not relevant to UIComplete. Please see a simple example using UI complete.
async function autocomplete() {
const sthings= await getSthings(); //gets json array, or ajax call, this is a promise
$("#sthHighlightSearch").autocomplete({
source: sthings
});
//This is an extension method for autocomplete
//Should filter the list with starts with characters written in the autocomplete
$.ui.autocomplete.filter = function (array, term) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(term), "i");
return $.grep(array, function (value) {
return matcher.test(value.label || value.value || value);
});
};
}
Here is a simplified version of my code :
function TextBox () {
this.builddom = function () {
// Building the text dom
}
}
function ImageBox () {
this.builddom = function () {
// Building the image dom
}
}
function Box (type) {
var handler =
(type == 'text') TextBox :
(type == 'Image') ImageBox : null;
if (handler) (handler).call (this);
this.builddom = function () {
// Here I would like to call the correct builddom function for the type.
}
}
var textbox = new Box ('text');
textbox.builddom ();
If Box.builddom doesn't exists, this works fine, the builddom function associated with the specific type is called. But I need to do some general thing in Box and then call the specific builddom. If I give a different name to Box builddom, say Box.dobuilddom, it is fine too, but breaks generic access to Boxes.
I think some clever prototype manipulation can do the job, but I was unable to find it.
Maybe would be better to avoid prototyping and use composition instead:
function TextBox(box) {
this.builddom = function() {
console.log('Building the text dom', box.props);
}
}
function ImageBox(box) {
this.builddom = function() {
console.log('Building the image dom', box.props);
}
}
function Box(props) {
this.props = props;
this.builddom = function() {
throw new Error('unsupported function');
}
}
var textbox = new TextBox(new Box({size:5}));
textbox.builddom();
I don't really understand the concept. The box is just some sort of container. It does not do anything but creates a new instance. What you'd really need here is a Box interface, but js does not have interfaces. You can use TypeScript if you want to...
function TextBox () {
this.builddom = function () {
// Building the text dom
}
}
function ImageBox () {
this.builddom = function () {
// Building the image dom
}
}
var container = {
createBox: function (type){
if (type == "text")
return new TextBox();
else if (type == "image")
return new ImageBox();
else
throw new Error();
}
};
var textbox = container.createBox('text');
textbox.builddom();
Another option is using proxy if you want to wrap objects, but I don't think that's your goal here.
If you need type check later, then you can use inheritance, but there is no multi inheritance, so even that way you cannot imitate interfaces. It goes this way btw.
function Box (){}
function TextBox () {}
TextBox.prototype = Object.create(Box.prototype, {
constructor:TextBox,
builddom: function () {
// Building the text dom
}
});
function ImageBox () {}
ImageBox.prototype = Object.create(Box.prototype, {
constructor:ImageBox,
builddom: function () {
// Building the image dom
}
});
var container = {
createBox: function (type){
if (type == "text")
return new TextBox();
else if (type == "image")
return new ImageBox();
else
throw new Error();
}
};
var textbox = container.createBox('text');
console.log(
textbox instanceof Box,
textbox instanceof ImageBox,
textbox instanceof TextBox
);
textbox.builddom();
If you want use prototyping, you can smth like this:
function TextBox(props) {
this.props = props;
}
TextBox.prototype = {
builddom: function () {
// Building the text dom
console.log("TextBox", this.props);
}
}
function ImageBox(props) {
this.props = props;
}
ImageBox.prototype = {
builddom: function () {
// Building the text dom
console.log("ImageBox", this.props);
}
}
function Box (type, props) {
var handler = (type == 'text') ? TextBox :
(type == 'Image') ? ImageBox : null;
if (handler) {
handler.call(this, props);
Object.assign(this, handler.prototype);
}
}
var textbox = new Box ('text', {text: 'some'});
textbox.builddom ();
var imagebox = new Box ('Image', {x: 1, y: 2});
imagebox.builddom ();
It's not clear why you don't just use standard prototype inheritance here. It will allow you to both inherit or override methods of the parent. For example, ImageBox inherits the parent method and TextBox overrides:
/* Define Box */
function Box (type) {
this.type = type || 'box'
}
Box.prototype.builddom = function (){
console.log(this.type, ": build called")
}
/* Define TextBox */
function TextBox () {
Box.call(this, "text")
}
TextBox.prototype = Object.create(Box.prototype);
/* Override method */
TextBox.prototype.builddom = function (){
// call parent method too?
// Box.prototype.builddom.call(this)
console.log(this.type, "Text box override method")
}
/* Define ImageBox */
function ImageBox () {
Box.call(this, "image")
}
ImageBox.prototype = Object.create(Box.prototype);
var box = new Box ();
box.builddom();
var textbox = new TextBox ();
textbox.builddom();
var imageBox = new ImageBox ();
imageBox.builddom();
There is no need to create a box class if you are not going to use it, instead create a factory function and return a new instance of the respective class.
function AbstractBox() {}
AbstractBox.prototype.builddom = function() {
console.warn("unimplemented method");
};
function TextBox() {}
TextBox.prototype.builddom = function() {
console.log("TextBox.builddom called");
};
function ImageBox() {}
ImageBox.prototype.builddom = function() {
console.log("ImageBox.builddom called");
};
function ErrorBox() {}
function createBox(type) {
var handler = Object.create(({
"text": TextBox,
"Image": ImageBox
}[type] || ErrorBox).prototype);
handler.constructor.apply(handler, [].slice.call(arguments, 1));
for (var property in AbstractBox.prototype) {
var method = AbstractBox.prototype[property];
if (typeof method === "function" && !(property in handler)) handler[property] = method;
}
return handler;
}
(createBox("text")).builddom(); // Text
(createBox("Image")).builddom(); // Image
(createBox("error")).builddom(); // Error
My suggestion is to use composition/delegation rather than inheritance (has-a instead of is-a).
function TextBox () {
this.builddom = function () {
// Building the text dom
}
}
function ImageBox () {
this.builddom = function () {
// Building the image dom
}
}
function Box (type) {
var constructor =
(type == 'text') ? TextBox :
(type == 'Image') ? ImageBox : null;
var delegate = new constructor();
this.builddom = function () {
// Pre-work goes here.
delegate.builddom();
// Post-work goes here.
}
}
var textbox = new Box ('text');
textbox.builddom ();
I am using the following code jsFiddle to work with form fields and events. I have previously asked two questions regarding this and they have helped me tremendously. Now I have a new problem/question.
function Field(args) {
this.id = args.id;
this.elem = document.getElementById(this.id);
this.value = this.elem.value;
}
Field.prototype.addEvent = function (type) {
this.elem.addEventListener(type, this, false);
};
// FormTitle is the specific field like a text field. There could be many of them.
function FormTitle(args) {
Field.call(this, args);
}
Field.prototype.blur = function (value) {
alert("Field blur");
};
FormTitle.prototype.blur = function () {
alert("FormTitle Blur");
};
Field.prototype.handleEvent = function(event) {
var prop = event.type;
if ((prop in this) && typeof this[prop] == "function")
this[prop](this.value);
};
inheritPrototype(FormTitle, Field);
var title = new FormTitle({name: "sa", id: "title"});
title.addEvent('blur');
function inheritPrototype(e, t) {
var n = Object.create(t.prototype);
n.constructor = e;
e.prototype = n
}
if (!Object.create) {
Object.create = function (e) {
function t() {}
if (arguments.length > 1) {
throw new Error("Object.create implementation only accepts the first parameter.")
}
t.prototype = e;
return new t
}
}
The problem is that I want to override the parent method (Field.prototype.blur) and instead use FormTitle.prototype.blur method for the title object. But the object keeps referencing the parent method and the alert always shows 'Field blur' instead of 'FormTitle Blur'. How can I make this work?
You are defining a method in the FormTitle prototype, then replacing the whole prototype with another object using inheritPrototype.
You have to swap the order. First you call this:
inheritPrototype(FormTitle, Field);
Then you set onblur on the prototype object you just created:
FormTitle.prototype.blur = function () {
alert("FormTitle Blur");
};
http://jsfiddle.net/zMF5e/2/
Here is my problem.
I am using Backbone js and every collection I have defined requires the same check on save or destroy. Except that the destroy success functions need to be passed an element to remove from the page when the destroy succeeds.
I didn't want to copy and paste the same code into every save or destroy method so I created this:
window.SAVE_TYPE_DESTROY = 'destroy';
window.SaveResponseHandler = function(el,type){
if (!type){
this.success = function() {
this._success();
};
}else if (type == window.SAVE_TYPE_DESTROY){
this.success = function() {
this._success();
$(el).remove();
};
}
};
SaveResponseHandler.prototype._success = function(model, response, options) {
if ((response.success * 1) === 0) {
persistError(model, {
responseText: response.message
}, {});
}
};
SaveResponseHandler.prototype.error = persistError;
var saveResponseHandler = new SaveResponseHandler();
And I use it like this:
destroy: function() {
var el = this.el;
var model = this.model;
this.model.destroy(new SaveResponseHandler(el,'destroy'));
},
change: function() {
this.model.set({
job_category_name: $($(this.el).find('input')[0]).val()
});
var viewView = this.viewView;
this.model.save(null, saveResponseHandler);
}
The problem is when success is called I get the following error:
Uncaught TypeError: Object [object Window] has no method '_success'
Any help will be much appreciated. I'm also open to any suggestions on better ways to handle this.
this inside of SaveResponseHandler.success isn't SaveResponseHandler, it's window.
window.SaveResponseHandler = function(el, type) {
var self = this;
if (!type) {
this.success = function() {
self._success();
};
} else if (type == window.SAVE_TYPE_DESTROY) {
this.success = function() {
self._success();
$(el).remove();
};
}
};
http://jsfiddle.net/ethagnawl/VmM5z/
I'm writing a lightweight jQuery plugin to detect dirty forms but having some trouble with events. As you can see in the following code, the plugin attaches an event listener to 'beforeunload' that tests if a form is dirty and generates a popup is that is the case.
There is also another event listener attached to that form's "submit" that should in theory remove the 'beforeunload' listener for that specific form (i.e. the current form I am submitting should not be tested for dirt, but other forms on the page should be).
I've inserted a bunch of console.log statements to try and debug it but no luck. Thoughts?
// Checks if any forms are dirty if leaving page or submitting another forms
// Usage:
// $(document).ready(function(){
// $("form.dirty").dirtyforms({
// excluded: $('#name, #number'),
// message: "please don't leave dirty forms around"
// });
// });
(function($) {
////// private variables //////
var instances = [];
////// general private functions //////
function _includes(obj, arr) {
return (arr._indexOf(obj) != -1);
}
function _indexOf(obj) {
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (obj, fromIndex) {
if (fromIndex == null) {
fromIndex = 0;
} else if (fromIndex < 0) {
fromIndex = Math.max(0, this.length + fromIndex);
}
for (var i = fromIndex, j = this.length; i < j; i++) {
if (this[i] === obj)
return i;
}
return -1;
};
}
}
////// the meat of the matter //////
// DirtyForm initialization
var DirtyForm = function(form, options) {
// unique name for testing purposes
this.name = "instance_" + instances.length
this.form = form;
this.settings = $.extend({
'excluded' : [],
'message' : 'You will lose all unsaved changes.'
}, options);
// remember intial state of form
this.memorize_current();
// activate dirty tracking, but disable it if this form is submitted
this.enable();
$(this.form).on('submit', $.proxy(this.disable, this));
// remember all trackable forms
instances.push(this);
}
// DirtyForm methods
DirtyForm.prototype = {
memorize_current: function() {
this.originalForm = this.serializeForm();
},
isDirty: function() {
var currentForm = this.serializeForm();
console.log("isDirty called...")
return (currentForm != this.originalForm);
},
enable: function() {
$(window).on('beforeunload', $.proxy(this.beforeUnloadListener, this));
console.log("enable called on " + this.name)
},
disable: function(e) {
$(window).off('beforeunload', $.proxy(this.beforeUnloadListener, this));
console.log("disable called on " + this.name)
},
disableAll: function() {
$.each(instances, function(index, instance) {
$.proxy(instance.disable, instance)
});
},
beforeUnloadListener: function(e) {
console.log("beforeUnloadListener called on " + this.name)
console.log("... and it is " + this.isDirty())
if (this.isDirty()) {
e.returnValue = this.settings.message;
return this.settings.message;
}
},
setExcludedFields: function(excluded) {
this.settings.excluded = excluded;
this.memorize_current();
this.enable();
},
serializeForm: function() {
var blacklist = this.settings.excludes
var filtered = [];
var form_elements = $(this.form).children();
// if element is not in the excluded list
// then let's add it to the list of filtered form elements
if(blacklist) {
$.each(form_elements, function(index, element) {
if(!_includes(element, blacklist)) {
filtered.push(element);
}
});
return $(filtered).serialize();
} else {
return $(this.form).serialize();
}
}
};
////// the jquery plugin part //////
$.fn.dirtyForms = function(options) {
return this.each(function() {
new DirtyForm(this, options);
});
};
})(jQuery);
[EDIT]
I ended up fixing this by using jQuery's .on() new namespace feature to identify the handler. The problem was that I was passing new anonymous functions as the handler argument to .off(). Thanks #FelixKling for your solution!
this.id = instances.length
[...]
enable: function () {
$(window).on('beforeunload.' + this.id, $.proxy(this.beforeUnloadListener, this));
},
disable: function () {
$(window).off('beforeunload.' + this.id);
},
Whenever you are calling $.proxy() it returns a new function. Thus,
$(window).off('beforeunload', $.proxy(this.beforeUnloadListener, this));
won't have any effect, since you are trying to unbind a function which was not bound.
You have to store a reference to the function created with $.proxy, so that you can unbind it later:
enable: function() {
this.beforeUnloadListener = $.proxy(DirtyForm.prototype.beforeUnloadListener, this);
$(window).on('beforeunload', this.beforeUnloadListener);
console.log("enable called on " + this.name)
},
disable: function(e) {
$(window).off('beforeunload', this.beforeUnloadListener);
console.log("disable called on " + this.name)
},