I'm new to Knockout. I have a Viewmodel like this:
var Booking = function(data) {
var self = this;
self.BookingID = ko.observable(data.BookingID);
self.BookingCustomerOrderID = ko.observable(data.BookingCustomerOrderID);
self.BookingName = ko.observable(data.BookingName);
self.BookingTreatmentGroupID = ko.observable(data.BookingTreatmentGroupID);
self.BookingStartTime = ko.observable(data.BookingStratTime);
self.BookingEndTime = ko.observable(data.BookingEndTime);
In my form I'd like to let the user change time of the StartTime and EndTime. Can I make a custom binding to just the time part leaving the datepart from the input field and make this update the model?
To just display the value this works fine, but this does not update the viewmodel.
ko.bindingHandlers.timeVal = {
update: function (element, valueAccessor) {
var value = valueAccessor();
var date = moment(value());
var strDate = date.format('HH:mm');
$(element).val(strDate);
}
};
Looking at the documentation, you can register an event handler onto the element in your init method, and use that to update your observable. Something like this:
ko.bindingHandlers.hasFocus = {
init: function(element, valueAccessor) {
$(element).change(function() {
if(this.val() != valueAccessor())
{
this.val(valueAccessor());
}
});
},
update: function(element, valueAccessor) {
var value = valueAccessor();
var date = moment(value());
var strDate = date.format('HH:mm');
$(element).val(strDate);
}
};
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);
});
};
}
For instance I have the following model:
var Volume = function (id, path, isactive) {
var self = this;
self.id = ko.observable(id);
self.path = ko.observable(path);
self.isactive = ko.observable(isactive);
self.Save = function (data) {
//ajax post
}
self.Update = function (data) {
//ajax post
}
}
var ViewModel = function (data) {
var self = this;
self.volumes = ko.observableArray(data.volumes.map(function (item) {
return new Volume(item.id, item.path, item.isActive, item.description);
}));
self.AddVolume = function () {
self.volumes.push(new Volume());
}
}
After Save or Update, I want to refresh the parent ViewModel from Volume model, because some values have changed in the database.
How do I reinitialize the ViewModel?
var viewModel = new ViewModel(ko.utils.parseJson(data) || []);
ko.applyBindings(viewModel);
You can have a function in your parent model which loads the new data and populates new data. Then anywhere you need to get the new data you simply call that function.
Example :
var Volume = function (data) {
var self = this;
self.id = ko.observable(data.id);
self.path = ko.observable(data.path);
self.isactive = ko.observable(data.isactive);
self.Save = function (data) {
//ajax post
//whenever you want to load data again you call viewModel.Load();
}
self.Update = function (data) {
//ajax post
//whenever you want to load data again you call viewModel.Load();
}
}
var ViewModel = function () {
var self = this;
self.volumes = ko.observableArray();
self.Load = function (){
//your ajax call or whatever you do to get the data
self.volumes($.map(data.volumes, function (item) {
return new Volume(item);
}
}
self.AddVolume = function () {
obj = {id:"",path:"",isactive:false}
// need to pass data to Volume model
self.volumes.push(new Volume(obj));
}
}
var viewModel = new ViewModel();
viewModel.Load();
ko.applyBindings(viewModel);
I'd suggest you to have save and update functions in your parent model and use $parent array object in order to reference.
I think you dont need to refresh the parent vm, If you need you can changes the particular index of the array from the value after update. Or call the getall method and push all the values after clearing the old values in the array(but it is not recomended). Or you can refresh the page. Choose wisely
I have a date time variable "whenDateTime" that is read from my db on the format (YYYY-MM-DDTHH:mm:ss.000).
I want to set a datetimepicker with this date time, then be able to manipulate it, and of course write it back to my db.
For some reason the datetimepicker will not trigger. Where do I go wrong?
This is my view model:
function ViewModel() {
var self = this;
self.whenDateTime = ko.observable("2016-04-09T19:24:48.000");
self.viewWhenDateTime = ko.computed({
read: function () {
var mydate = self.whenDateTime();
if (!mydate) {
return null;
} else {
return moment(mydate).format("DD.MM.YYYY HH:mm");
}
},
write: function (newVal) {
var reversed = moment(newVal).format();
self.whenDateTime(reversed);
}
});
}
The bindingHandlers is like this:
ko.bindingHandlers.dateTimePicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().dateTimePickerOptions || {};
$(element).datetimepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "dp.change", function (event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
if (event.date != null && !(event.date instanceof Date)) {
value(event.date.toDate());
} else {
value(event.date);
}
}
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
var picker = $(element).data("DateTimePicker");
if (picker) {
picker.destroy();
}
});
},
update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var picker = $(element).data("DateTimePicker");
//when the view model is updated, update the widget
if (picker) {
var koDate = ko.utils.unwrapObservable(valueAccessor());
//in case return from server datetime i am get in this form for example /Date(93989393)/ then fomat this
koDate = (typeof (koDate) !== 'object') ? new Date(parseFloat(koDate.replace(/[^0-9]/g, ''))) : koDate;
picker.date(koDate);
}
}
};
Fiddle: http://jsfiddle.net/AsleG/v54hnxur/
When I run the fiddle (https://jsfiddle.net/9aLvd3uw/237/), it actually shows 09/04/2016 7:24 PM for 2016-04-09T19:24:48.000 and when I change the input date it gets changed properly. I couldn't replicate what you mentioned.
Note whenever moment.js wants to parse a date if that date is undefined or provided in a wrong format, it displays the current date instead.
I am having difficulties with this handler I have partially gotten from here and partially hacked together. I am still getting my bearings on the handlers so I am assuming my issues is stemming from a lack of understanding.
I am using this handler in a template that is displayed inside a ko "if" statement. When the template is being included/excluded on and off options are duplicating. This is because of the unwrap(valueAccessor()).push(item) line. I have tried just building the array independantly and then setting the valueAccessors value to the array directly but the ui does not respond, it only works by pushing the items.
How can I get around this? Am I doing the binding correctly or is there a better more appropriate way? I have marked the line of code with a comment to indicate where my problem is happening.
multiSelectCheck: {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called when the binding is first applied to an element
// Set up any initial state, event handlers, etc. here
var bindings = allBindingsAccessor();
var ddOptions = unwrap(valueAccessor);
var selectedOptions = unwrap(bindings.selectedOptions);
var options = unwrap(bindings.multiselectOptions) || [];
var optionsCaption = unwrap(bindings.optionsCaption);
var displaySelected = unwrap(bindings.selectedList) || 5;
var loadingCaption = unwrap(bindings.loadingCaption);
var delimiter = unwrap(bindings.splitSelectedBy) || ',';
var setInitial = unwrap(bindings.setInitialValue);
// display loader in dropdown
ko.computed(function () {
if (unwrap(bindings.loading)) {
var spinnerClass = 'fa fa-spinner fa-spin fa-lg';
var spinner = loadingCaption || '<span><i class="' + spinnerClass + '"></i> Loading...</span>';
// set text to loading
$(element).multiselect({ selectedList: 0, noneSelectedText: spinner, selectedText: spinner }).multiselect('disable');
$(element).multiselect('refresh');
}
}, null, { disposeWhenNodeIsRemoved: element });
// internal options
var internal = { selectedList: displaySelected, noneSelectedText: 'Select options', selectedText: '# selected' }
// merge options with provided options
options = $.extend(internal, options);
// pass the original optionsCaption to the similar widget option
if (optionsCaption) {
options.noneSelectedText = unwrap(optionsCaption);
}
// remove this and use the widget's
bindings.optionsCaption = '';
// populate intitial values if available
if (ddOptions && !ddOptions.length && setInitial) {
if (selectedOptions) {
// create array from value
if (typeof selectedOptions == 'string') {
selectedOptions = selectedOptions.split(delimiter);
selectedOptions = selectedOptions.filter(function (e) { return !!e; }); // filter empty nodes
bindings.selectedOptions(selectedOptions);
}
// add options objects to array of available options
for (var i = 0; i < selectedOptions.length; i++) {
var item = { Value: selectedOptions[i], Text: '' };
//console.log(item);
//#### THIS IS THE LINE OF CODE IN QUESTION ####
unwrap(valueAccessor()).push(item);
}
}
}
// apply multiselect plugin
var elm = $(element).multiselect(options).multiselectfilter({ filterOnly: true, autoReset: true });
// refresh the plugin
$(element).multiselect('refresh');
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
elm.multiselectfilter('destroy').multiselect("destroy");
$(element).remove();
});
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
// This will be called once when the binding is first applied to an element,
// and again whenever the associated observable changes value.
// Update the DOM element based on the supplied values here.
var bindings = allBindingsAccessor();
var selectOptions = unwrap(bindings.multiSelectCheck);
var selectedOptions = unwrap(bindings.selectedOptions);
var delimiter = unwrap(bindings.splitSelectedBy) || ',';
var displaySelected = unwrap(bindings.selectedList) || 5;
// remove this and use the widget's
bindings.optionsCaption = '';
// handle delimited values
if (typeof selectedOptions == 'string') {
selectedOptions = selectedOptions.split(delimiter);
selectedOptions = selectedOptions.filter(function (e) { return !!e; }); // filter empty nodes
bindings.selectedOptions(selectedOptions);
}
ko.bindingHandlers.options.update(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext);
var data = unwrap(valueAccessor());
var showFilter = (data && data.length > 10) ? 'enable' : 'disable';
setTimeout(function () {
var $element = $(element);
$element.multiselect({ selectedList: displaySelected, noneSelectedText: 'Select options', selectedText: '# selected' }).multiselect('enable').multiselect('refresh').multiselectfilter('refresh');
$element.multiselectfilter(showFilter);
$element.multiselect('refresh');
}, 0);
}
}
Try to create temporary array with items and update valueAccessor observable array directly:
var items = [];
for (var i = 0; i < selectedOptions.length; i++) {
items.push({ Value: selectedOptions[i], Text: '' });
}
// items
valueAccessor(items);
So my problem ended up being that I thought I had the array value, but I ended up having the observable instead. This caused my array length check to always pass so it kept adding the initial values.
I had to change the init line
var ddOptions = unwrap(valueAccessor);
To
var ddOptions = unwrap(valueAccessor()); // added () :/
So I bind my Knockout template as follows:
First ajax, get data then I pass the data can call a function named bindKo:
function bindKo(data) {
var length = data.length;
var insertRecord = {};
if (length > 0) {
insertRecord = data[data.length - 1]; //last record is an empty PremlimViewModel for insert
insertRecord.Add = true;
data.splice(data.length - 1, 1); //remove that blank insert record
}
function prelims(data) {
var self = this;
var model = ko.mapping.fromJS(data, { copy: ["_destroy"] }, self);
self.BidPriceFormatted = ko.computed({
read: function () {
var bidPrice = this.BidPrice();
if (bidPrice) {
if (!isNaN(bidPrice)) {
var input = '<input type="text" value="' + bidPrice + '"/>';
return $(input).currency({ decimals: 0 }).val();
}
}
},
write: function (value) {
value = value.replace(/\D/g, '');
this.BidPrice(value);
},
owner: this
});
return model;
}
var mapping = {
create: function (options) {
return new prelims(options.data);
}
};
function viewModel(prelimData) {
var self = this;
self.prelims = ko.mapping.fromJS(prelimData, mapping);
self.remove = function (prelim) {
self.prelims.destroy(prelim);
};
self.addOption = function () {
var clone = jQuery.extend(true, {}, insertRecord);
self.prelims.push(ko.mapping.fromJS(clone));
};
}
ViewModel = new viewModel(data);
ko.applyBindings(ViewModel);
}
I have a template defined where you can add and remove records, and user does just that:
<script type="text/html" id="PrelimsTemplate">
<!--Template Goodness-->
</script>
Then, ajax call, records updated in datanbase, latest results returned and I do:
ko.mapping.fromJS(newestData, ViewModel)
But this does not work because my ViewModel is complex.
So I would just like to reBind the template entirely. Make is disappear and reappear with latest data.
Wrap your template in a container than you can hook onto with jQuery.
When you need to trash it use ko.cleanNode and jQuery .empty()
emptyTemplate: function(){
ko.cleanNode($('#template-container')[0]);
$('#template-container').empty();
}
Load your template back up
fillTemplate: function(){
$('#template-container').html('<div data-bind="template: {name:\'templateId\', data: $data}"></div>');
ko.applyBindings(data,$('#template-container')[0])
},
See my fiddle