Using jQuery UI datepicker with hour / minute dropdowns with KnockoutJS - jquery-ui

I've got a view model that looks like this:
var ViewModel = function() {
var self = this;
self.hourOptions = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23];
self.minuteOptions = [0, 15, 30, 45];
self.formatTimeOption = function(hour) {
if (hour < 10) return "0" + hour;
return hour.toString();
};
self.startDate = ko.observable(null);
self.startDateHour = ko.computed({
read: function() {
return new Date(self.startDate()).getHours();
},
write: function(value) {
var newDate = new Date(self.startDate());
newDate.setHours(value);
self.startDate(newDate);
}
});
self.startDateMinute = ko.computed({
read: function() {
return new Date(self.startDate()).getMinutes();
},
write: function(value) {
var newDate = new Date(self.startDate());
newDate.setMinutes(value);
self.startDate(newDate);
}
});
};
As you can see, I've got a writeable computed observable that updates the startDate hours / minutes when updated.
This is working, however when it does so, the datepicker input field displays the long form of the date, rather than (for example)
01/03/2013
JSFiddle of this is available here: http://jsfiddle.net/alexjamesbrown/2kSpL/9/

I solved this by adding the following custom binding handler, as taken from this answer
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//handle the field changing
ko.utils.registerEventHandler(element, "change", function() {
var observable = valueAccessor();
observable($(element).datepicker("getDate"));
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).datepicker("destroy");
});
},
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor()),
current = $(element).datepicker("getDate");
if (value - current !== 0) {
$(element).datepicker("setDate", value);
}
}
};
Here's a working JSFiddle:
http://jsfiddle.net/alexjamesbrown/v6hdS/

Related

Highcharts low performance when adding yAxis dynamically

I am trying to add/delete yAxis dynamically but I observe performance issues. It takes more than a second (sometimes it goes upto 4 seconds) to dynamically add or remove a series into a new yAxis. I need to load end of day data (price point for each day) for 10 or more years in the chart.
Any advice in improving the performance will be much appreciated.
Few points to note -
I can use different type of charts (line, ohlc, candlestick, area etc.)
I need mouse tracking to be enabled as I am using click events on the series.
User will have option to either choose to apply data grouping or to not.
Below is my code sample to illustrate the problem.
var chart;
var index = 2;
var groupingUnitsD = {units:[['day',[1]]], enabled:true};
var groupingUnitsWM = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$(function () {
var ohlc = [];
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) {
// split the data set into ohlc
var volume = [],
dataLength = data.length,
i = 0;
for (i; i < dataLength; i++) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
}
loadChart(data);
});
function loadChart(cdata){
var highchartOptions = {
plotOptions:{
line: {
enableMouseTracking: true,
animation:false,
marker: {
enabled: false
}
},
series:{
cursor: 'pointer',
}
},
chart:{
renderTo:'container'
},
navigator: {
outlineColor: '#0066DD',
outlineWidth: 1
},
xAxis: [{
gridLineWidth: 1,
gridLineColor: "#eaf5ff",
lineColor: '#FF0000',
lineWidth: 1
}],
yAxis:[{
title:{
text:"initial data"
},
id:'myaxis-1',
height:'14%',
top:'0%'
}],
series: [{
data: cdata,
turboThreshold:0,
dataGrouping:groupingUnitsD
}]
};
chart = new Highcharts.StockChart(highchartOptions);
}
$button = $('#button');
$delButton = $('#delbutton');
$button.click(function () {
var axisObj = {
title: {
text: "axis-" + index,
},
id:'myaxis-'+ index
};
chart.addAxis(axisObj, false);
console.log("Added axis:" + 'myaxis-'+ index);
$('#axisList').append($('<option></option>').text('myaxis-'+ index));
var seriesData = new Object();
seriesData.name = 'axis-' + index;
seriesData.id = 'myaxis-' + index;
seriesData.yAxis = 'myaxis-'+ index;
seriesData.data = ohlc;
seriesData.type = 'line';
seriesData.dataGrouping = groupingUnitsD;
chart.addSeries(seriesData);
updateAxisHeight();
index++;
});
$delButton.click(function () {
var $select = $('#axisList');
console.log($select.val());
console.log(chart.get($select.val()));
var selId = $select.val();
chart.get(selId).remove();
$('option:selected', $select).remove();
var i=0;
updateAxisHeight();
});
updateAxisHeight = function(){
var i=0;
$("#axisList > option").each(function() {
chart.get(this.value).update({ height: '14%',top: (i*15) + '%',offset:0 });
i++;
});
}
});
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<button id="button" class="autocompare">Add yAxis</button><br>
<!--Entrt yAxis index to delete:<input type='text' id="delAxis"/> -->
<select id="axisList" name="axisList">
<option value="myaxis-1" selected="selected">myaxis-1</option>
</select>
<button id="delbutton" class="autocompare">Delete yAxis</button>
<div id="container" style="height: 800px"></div>
You can significantly improve the performance in this case with one trick: when performing several consecutive operations that each require a redraw (add series, add axis, update axis height), don't redraw until you've told Highcharts about all the operations.
On my machine, this improves the performance of your add axis function by 5x-6x. See code and comments below.
var chart;
var index = 2;
var groupingUnitsD = {units:[['day',[1]]], enabled:true};
var groupingUnitsWM = [[
'week', // unit name
[1] // allowed multiples
], [
'month',
[1, 2, 3, 4, 6]
]];
$(function () {
var ohlc = [];
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-ohlcv.json&callback=?', function (data) {
// split the data set into ohlc
var volume = [],
dataLength = data.length,
i = 0;
for (i; i < dataLength; i++) {
ohlc.push([
data[i][0], // the date
data[i][1], // open
data[i][2], // high
data[i][3], // low
data[i][4] // close
]);
}
loadChart(data);
});
function loadChart(cdata){
console.time("chart load");
var highchartOptions = {
plotOptions:{
line: {
enableMouseTracking: true,
animation: false,
marker: {
enabled: false
}
},
series:{
cursor: 'pointer',
}
},
chart:{
alignTicks: false,
events: {
load: function () {
console.timeEnd("chart load");
}
},
renderTo:'container'
},
yAxis:[{
title:{
text:"initial data"
},
id:'myaxis-1',
height:'14%',
top:'0%'
}],
series: [{
data: cdata,
turboThreshold:0,
dataGrouping:groupingUnitsD
}]
};
chart = new Highcharts.StockChart(highchartOptions);
}
$button = $('#button');
$delButton = $('#delbutton');
$button.click(function () {
var startTime = new Date().getTime();
var axisObj = {
title: {
text: "axis-" + index,
},
id:'myaxis-'+ index
};
chart.addAxis(axisObj, false, false); // don't redraw yet
console.log("Added axis:" + 'myaxis-'+ index);
$('#axisList').append($('<option></option>').text('myaxis-'+ index));
var seriesData = new Object();
seriesData.name = 'axis-' + index;
seriesData.id = 'myaxis-' + index;
seriesData.yAxis = 'myaxis-'+ index;
seriesData.data = ohlc;
seriesData.type = 'line';
seriesData.dataGrouping = groupingUnitsD;
chart.addSeries(seriesData, false); // don't redraw yet
updateAxisHeight(false); // don't redraw yet
index++;
// finally, redraw now
chart.redraw();
var endTime = new Date().getTime();
console.log("add axis took " + (endTime - startTime) + " msec");
});
$delButton.click(function () {
var $select = $('#axisList');
console.log($select.val());
console.log(chart.get($select.val()));
var selId = $select.val();
chart.get(selId).remove();
$('option:selected', $select).remove();
var i=0;
updateAxisHeight();
});
updateAxisHeight = function(redraw){
// set redraw to true by default, like Highcharts does
if (typeof redraw === 'undefined') {
redraw = true;
}
var i=0;
$("#axisList > option").each(function() {
// don't redraw in every iteration
chart.get(this.value).update({ height: '14%',top: (i*15) + '%',offset:0 }, false);
i++;
});
// redraw if caller asked to, or if the redraw parameter was not specified
if (redraw) {
chart.redraw();
}
}
});
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.highcharts.com/stock/highstock.js"></script>
<script src="http://code.highcharts.com/stock/highcharts-more.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<button id="button" class="autocompare">Add yAxis</button><br>
<!--Entrt yAxis index to delete:<input type='text' id="delAxis"/> -->
<select id="axisList" name="axisList">
<option value="myaxis-1" selected="selected">myaxis-1</option>
</select>
<button id="delbutton" class="autocompare">Delete yAxis</button>
<div id="container" style="height: 800px"></div>

knockout databind with jqueryUI based dateRangePicker

I'm using a jQuery UI based dateRangePicker which I am trying to bind with a KnockoutJS based viewModel via a custom binder. But I am not even able to make the dateRangePicker read an observable like
this.range = ko.observable("Jul 1,2015 - Jul 3,2015");
Here is my JSFiddle attempt. Is that a wrong approach and do I need create something like this
this.startDate
this.endDate
The dateRangePicker documentation states that it stores an object with the following properties: start and end. It stores this as a JSON string in the value field of the <input> element that is used to contain dateRangePicker. Therefore, you probably want your range observable to also store an object with start and end properties. I wrote a custom binding which will apply the dateRangePicker to an element and will write the object into your observable any time a different selection is made:
ko.bindingHandlers.dateRangePicker = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var $el = $(element);
$el.daterangepicker({
onChange: function() {
var range = JSON.parse($el.val());
valueAccessor()(range);
}
});
var value = valueAccessor()();
if (value) {
var range = {"start": new Date(value["start"] + " 00:00:00")};
if (value["end"]) {
range["end"] = new Date(value["end"] + " 00:00:00");
}
$el.daterangepicker("setRange", range);
}
}
};
You can then apply this to your <input> element:
<input id="e1" data-bind="dateRangePicker: range">
If you need to initialize the value on the dateRangePicker through the viewmodel, then you need to store an object into the range observable that matches the format that the dateRangePicker uses:
this.range = ko.observable({start:"2015-07-01", end:"2015-07-03"});
Here is a fiddle: http://jsfiddle.net/efywmomz/
Update
I altered the custom binding to use the moment library and updated the fiddle to initialize the range from the viewmodel: http://jsfiddle.net/efywmomz/1/
ko.bindingHandlers.dateRangePicker = {
init: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
var $el = $(element);
$el.daterangepicker({
onChange: function() {
var range = JSON.parse($el.val());
valueAccessor()(range);
}
});
var value = valueAccessor()();
if (value) {
var range = {"start": moment(value["start"])._d};
if (value["end"]) {
range["end"] = moment(value["end"])._d;
}
$el.daterangepicker("setRange", range);
}
}
};
Here is a sample which i've implemented with moment js library and daterangepicker js library with knockout
HTML
<div id="reportrange" class="pull-right" data-bind="BindRangeDatePicker: Value">
<i class="fa fa-calendar fa-lg"></i>
<input type="text" data-bind="value: Value" readonly />
<span data-bind="text: Value"></span><b class="caret"></b>
</div>
knockout
ko.bindingHandlers.BindRangeDatePicker = {
init: function (element, valueAccessor, allBindings, vm, context) {
$(element).daterangepicker(
{
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
'Last 7 Days': [moment().subtract('days', 6), moment()],
'Last 30 Days': [moment().subtract('days', 29), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
},
startDate: moment().subtract('days', 29),
endDate: moment()
}, function (start, end) {
$(element).find('span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
);
},
update: function (element, valueAccessor, allBindings, vm, context) {
var value = valueAccessor();
$(element).daterangepicker(
{
ranges: {
'Today': [moment(), moment()],
'Yesterday': [moment().subtract('days', 1), moment().subtract('days', 1)],
'Last 7 Days': [moment().subtract('days', 6), moment()],
'Last 30 Days': [moment().subtract('days', 29), moment()],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
},
startDate: moment().subtract('days', 29),
endDate: moment()
}, function (start, end) {
//var val = start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY');
//valueAccessor(val.toString());
$(element).find('span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
}
);
}
}

updating template of child scope from parent scope in angular js

I have this fiddle example where I am trying to set a value in an ng-repeat that lives in a different scope. This is a very basic example of a much bigger issue I am trying to solve. Basically I need to set a variable in the ng-repeat so that angular will update the template accordingly. The problem is that the template is in a child controller. So i use the $controller inject-able to access the variable. However, updating this variable does not cause the template to update. Even if I do a scope.$apply(). Anyone have any ideas? I am unsure on another way to do this...
var myApp = angular.module('myApp', []);
myApp.directive("custdirective", function() {
return {
restrict: 'A',
scope: 'false',
link: function(scope, element, attr) {
element.on("click", function() {
anotherscope.addList();
});
}
}
});
function AnotherController($scope) {
$scope.listtwo = new Array();
$scope.addList = function() {
$scope.listtwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
}
}
function MyCtrl($scope, $controller, $rootScope) {
anotherscope = $rootScope.$new();
$scope.anothercontroller = $controller(AnotherController, {
$scope: anotherscope
});
}​
To do this correctly, one would create a service. I made an updated fiddle of the correct way to do this here or:
var myApp = angular.module('myApp', []);
myApp.factory("mySharedService", function($rootScope) {
var sharedService = {};
sharedService.message = '';
sharedService.prepForBroadcast = function() {
this.message = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
this.broadcastItem();
};
sharedService.broadcastItem = function() {
$rootScope.$broadcast('handleBroadcast');
};
return sharedService;
});
myApp.directive("custdirective", function() {
return {
restrict: 'A',
scope: 'false',
link: function(scope, element, attr) {
element.on("click", function() {
debugger;
scope.handleClick();
});
}
}
});
function AnotherController($scope, sharedService) {
$scope.listtwo = new Array();
$scope.addList = function() {
$scope.listtwo = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
}
$scope.$on('handleBroadcast', function() {
$scope.listtwo = sharedService.message;
$scope.$apply();
});
}
function MyCtrl($scope, sharedService) {
$scope.handleClick = function() {
sharedService.prepForBroadcast();
};
}
MyCtrl.$inject = ['$scope', 'mySharedService'];
AnotherController.$inject = ['$scope', 'mySharedService'];​
Passing scopes around like that is a little wonky, and is almost guaranteed to break the testability of your Angular application.
I think you'd be better off creating a service that brokered changes between your controllers and your directive. The service would contain either the arrays you wished to update, or the functions you wished to call from your directive.
I'm afraid it's hard to write up an example of such a service, as I don't really understand what your ultimate goal is.

Using knockout js with jquery ui sliders

I'm trying to figure out if knockout js would work nicely for the following problem:
I have multiple sliders that I want to link to textboxes.
When the textbox is changed the corresponding slider must update to the new value and vice versa.
On changing the slider value or textbox a function needs to be called that uses the input from all textboxes to calculate a result.
I have my quick and dirty jQuery solution here.
Would it be easy to achieve the same result in a more elegant way using knockout js?
I guess I would need to create a custom binding handler like its done in jQuery UI datepicker change event not caught by KnockoutJS
Here is an example: http://jsfiddle.net/jearles/Dt7Ka/
I use a custom binding to integrate the jquery-ui slider and use Knockout to capture the inputs and calculate the net amount.
--
UI
<h2>Slider Demo</h2>
Savings: <input data-bind="value: savings, valueUpdate: 'afterkeydown'" />
<div style="margin: 10px" data-bind="slider: savings, sliderOptions: {min: 0, max: 100, range: 'min', step: 1}"></div>
Spent: <input data-bind="value: spent, valueUpdate: 'afterkeydown'" />
<div style="margin: 10px" data-bind="slider: spent, sliderOptions: {min: 0, max: 100, range: 'min', step: 1}"></div>
Net: <span data-bind="text: net"></span>
View Model
ko.bindingHandlers.slider = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
$(element).slider({
"slide": function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
},
"change": function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
}
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
},
update: function (element, valueAccessor) {
var value = ko.unwrap(valueAccessor());
if (isNaN(value)) {
value = 0;
}
$(element).slider("value", value);
}
};
var ViewModel = function() {
var self = this;
self.savings = ko.observable(10);
self.spent = ko.observable(5);
self.net = ko.computed(function() {
return self.savings() - self.spent();
});
}
ko.applyBindings(new ViewModel());
I know it's some days ago but I made a few adjustments to John Earles code:
ko.bindingHandlers.slider = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
ko.utils.registerEventHandler(element, "slide", function (event, ui) {
var observable = valueAccessor();
observable(ui.value);
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (isNaN(value)) value = 0;
$(element).slider("option", allBindingsAccessor().sliderOptions);
$(element).slider("value", value);
}
};
The reason for this is that if you use options that change (fx another observable) then it won't affect the slider even if you wanted it to do so.
#John Earles and #Michael Kire Hansen: thanks for your wonderful solutions!
I used the advanced code from Michael Kire Hansen. I tied the "max:" option of the slider to a ko.observable and it turned out that the slider does not correctly update the value in this case. Example: Lets say the slider is at value 25 of max 25 und you change the max value to 100, the slider stays at the most right position, indicating that it is at the max value (but value is still 25, not 100). As soon as you slide one point to the left, you get the value updated to 99.
Solution:
in the "update:" part just switch the last two lines to:
$(element).slider("option", allBindingsAccessor().sliderOptions);
$(element).slider("value", value);
This changes the options first, then the value and it works like a charm.
Thanks so much for the help, I needed to use a range slider in my scenario so here is an extension to #John Earles and #Michael Kire Hansen
ko.bindingHandlers.sliderRange = {
init: function (element, valueAccessor, allBindingsAccessor) {
var options = allBindingsAccessor().sliderOptions || {};
$(element).slider(options);
ko.utils.registerEventHandler(element, "slidechange", function (event, ui) {
var observable = valueAccessor();
observable.Min(ui.values[0]);
observable.Max(ui.values[1]);
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).slider("destroy");
});
ko.utils.registerEventHandler(element, "slide", function (event, ui) {
var observable = valueAccessor();
observable.Min(ui.values[0]);
observable.Max(ui.values[1]);
});
},
update: function (element, valueAccessor, allBindingsAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
if (isNaN(value.Min())) value.Min(0);
if (isNaN(value.Max())) value.Max(0);
$(element).slider("option", allBindingsAccessor().sliderOptions);
$(element).slider("values", 0, value.Min());
$(element).slider("values", 1, value.Max());
}
};
and then the HTML to accompany it
<div id="slider-range"
data-bind="sliderRange: { Min: 0, Max: 100 },
sliderOptions: {
range: true,
min: 0,
max: 100,
step: 10,
values: [0, 100]
}"></div>

JQuery UI - Set minTime on timepicker based on other timepicker value

I'm trying to set the minTime of my End Time timepicker based on what I've selected in the Start Time timepicker.
I have this, based on something that works for the regular datepicker, but it's not working.
$('#confirmed_time_start').timepicker({
timeFormat: 'hh:mm',
stepHour: 1,
stepMinute: 15,
hour: 8,
minute: 0,
hourMin: 8,
hourMax: 18,
onSelect: function(timeStr) {
var newTime = $(this).timepicker('getDate');
if (newTime) { // Not null
newTime.setDate(newTime.getDate());
}
$('#confirmed_time_end').timepicker('minTime', newTime)
}
});
$('#confirmed_time_end').timepicker({
timeFormat: 'hh:mm',
stepHour: 1,
stepMinute: 15,
hour: 8,
minute: 0,
hourMin: 8,
hourMax: 18
});
The error I'm receiving is:
Object doesn't support this property or method
var time = new Date();
$('#from').timepicker({
ampm: true,
hourMin: 9,
hourMax: 19,
timeFormat: 'hh:mm TT',
onClose: function(dateText, inst) {
var startDateTextBox = $('#to');
if (startDateTextBox.val() != '') {
var testStartDate = new Date(startDateTextBox.val());
var testEndDate = new Date(dateText);
if (testStartDate > testEndDate)
startDateTextBox.val(dateText);
}
else {
startDateTextBox.val(dateText);
}
},
onSelect: function(dateText){
var time = new Date($(this).datetimepicker('getDate').getTime());
$('#to').timepicker('option', 'minDateTime',time);
}
});
$('#to').timepicker({
ampm: true,
hourMin: 10,
hourMax: 21,
timeFormat: 'hh:mm TT',
onClose: function(dateText, inst) {
var startDateTextBox = $('#from');
if (startDateTextBox.val() != '') {
var testStartDate = new Date(startDateTextBox.val());
var testEndDate = new Date(dateText);
if (testStartDate > testEndDate)
startDateTextBox.val(dateText);
}
else {
startDateTextBox.val(dateText);
}
},
onSelect: function(dateText){
var time = new Date($(this).datetimepicker('getDate').getTime());
$('#from').timepicker('option', 'maxDateTime',time);
}
});
$('#confirmed_time_start').timepicker({
timeFormat: 'hh:mm',
stepHour: 1,
stepMinute: 15,
hour: 8,
minute: 0,
hourMin: 8,
hourMax: 18,
onSelect: function(timeStr) {
var newTime = $(this).timepicker('getDate');
if (newTime) { // Not null
newTime.setDate(newTime.getDate());
}
$('#confirmed_time_end').timepicker('setTime', newTime);
}
});

Resources