moment datapicker: subcription to KO property - javascript

Working with moment datepicker in my project i can't see where my error is.
Basically what i want to do is make a suscription to source property in order to know when th property change (the time to load to service method). So follwoing some urls i was able to build this basic example:
var model = {
test_date: ko.observable(new Date('2012/12/12'))
};
ko.applyBindings(model, $("#target")[0]);
model.test_date.subscribe(function (newValue) {
alert("new selection :" + newValue);
});
http://jsfiddle.net/rolandomartinezg/x7Zt3/5/
The code above is simple and works, my trouble begin in my production code where for some strange reason the code realted to suscription is not fired.
short example (in production code I am typescript):
export var fromDate = ko.observable(new Date('2012/12/12'));
fromDate.subscribe(function (newValue) {
alert("new selection of date");
});
I tried find some missing reference from my jsfiddle example and my production code and both are using the same libraries (moment.js, moment-datepicker.js, moment-datepicker-ko.js,/knockout.js.
what i am doing wrong? any tip?
UPDATE 1: My production code converted from typescript to js:
define(["require", "exports", 'services/logger', '../../services/Assessment/datacontext'], function(require, exports, __logger__, __datacontext__) {
var logger = __logger__;
var datacontext = __datacontext__;
exports.title = 'AssessmentListing';
exports.fromDate = ko.observable(new Date('2012/12/12'));
exports.toDate = ko.observable(new Date('2012/12/12'));
function activate() {
loadInitData();
}
exports.activate = activate;
function loadInitData() {
var focusDate = ko.observable(new Date('2013/07/06'));
exports.fromDate = ko.observable(firstDayOfMonth(focusDate));
exports.toDate = ko.observable(getLastDayOfMonth(focusDate));
// calls to services
}
function getLastDayOfMonth(focusDate) {
var d = new Date(Date.apply(null, focusDate));
d.setMonth(d.getMonth() + 1);
d.setDate(0);
return d;
}
function firstDayOfMonth(focusDate) {
var d = new Date(Date.apply(null, arguments));
d.setDate(1);
return d;
}
exports.toDate.subscribe(function (newValue) {
alert("new selection :");
});
exports.fromDate.subscribe(function (newValue) {
alert("new selection");
});
function viewAttached() {
}
exports.viewAttached = viewAttached;
})
UPDATE 2: My VIEW
<div class="span4">
<span><small>From Date:</small> </span>
<div class="input-append date" id="fromDate" >
<input id="fromDatePicker" type="text" data-bind="datepicker: fromDate()" class="input-small">
<span class="add-on"><i class="icon-calendar"></i></span>
</div>
<span><small>To Date: </small></span>
<div class="input-append date" id="ToDate" >
<input id="toDatePicker" type="text" data-bind="datepicker: toDate()" class="input-small">
<span class="add-on"><i class="icon-calendar"></i></span>
</div>
</div>
Update 3
Trying use changeDate doesn't work because ev.date is not available.
export function viewAttached() {
$('#fromDatePicker').datepicker()
.on('changeDate', function (ev) {
/*ev.date doesn't work*/
alert('fromdate has changed');
});
}

In your data binding, you have:
datepicker: toDate()
Since toDate is an observable, calling toDate() gets you the value of the observable, so you're passing that instead of passing the observable itself.
Try changing your binding to:
datepicker: toDate
That will enable the datepicker binding handler to update your observable.
Update:
I think this is your second problem. In this function:
function loadInitData() {
var focusDate = ko.observable(new Date('2013/07/06'));
exports.fromDate = ko.observable(firstDayOfMonth(focusDate));
exports.toDate = ko.observable(getLastDayOfMonth(focusDate));
// calls to services
}
...you are replacing the toDate and fromDate properties with new observables which do not have the subscriptions applied that the original observables do. Try attaching the subscriptions after creating these observables, or perhaps instead of creating new observables, just populate them:
function loadInitData() {
var focusDate = ko.observable(new Date('2013/07/06'));
exports.fromDate(firstDayOfMonth(focusDate));
exports.toDate(getLastDayOfMonth(focusDate));
// calls to services
}

Related

Knockout multiple dynamic text boxes with one observable array

I am trying to save the data from the text-boxes to the localStorage using knockout JS! However I am new and not able to figure out this particular scenario. The field has same observable name! Please find my code below.
HTML Code:
<form data-bind="foreach: trialData">
<input type="text" name="name" data-bind="textInput: myData"><br>
</form>
JS Code:
var dataModel = {
myData: ko.observable('new'),
dataTemplate: function (myData) {
var self = this;
self.myData = ko.observable(myData);
}
};
dataModel.collectedNotes = function () {
var self = this;
self.trialData = ko.observableArray([]);
for (var i=0; i<5; i++) {
self.trialData.push (new dataModel.dataTemplate());
}
};
dataModel.collectedNotes();
ko.applyBindings(dataModel);
Traget: The data entered inside the text-boxes should be available in localStorage.
You need to define a Handler function to read the data from the Textboxes and save it to the localstorage. You need to reference the Data which is bound to the click event, which can be accessed using the first parameter. Knockout passes the data and event information as 2 arguments to the click handler function. So, you can add the event handler to your viewModel using the click binding and then unwrap the value and save it to localStorage.
saveToLocalStorage : function(data){
var datatoStore = JSON.stringify(data.trialData().map(x=>x.myData()));
console.log(datatoStore);
localStorage.setItem("TextBoxValue", datatoStore);
}
Complete Code: Please note since this is a sandboxed environment (Running this js Snippet on StackOverflow), localStorage wouldn't work, but it should work in your code. I have added a line in console to get the value to Store.
var dataModel = {
myData: ko.observable('new'),
dataTemplate: function (myData) {
var self = this;
self.myData = ko.observable(myData);
},
saveToLocalStorage : function(data){
var datatoStore = JSON.stringify(data.trialData().map(x=>x.myData()));
console.log(datatoStore);
localStorage.setItem("TextBoxValue", datatoStore);
}
};
dataModel.collectedNotes = function () {
var self = this;
self.trialData = ko.observableArray([]);
for (var i=0; i<5; i++) {
self.trialData.push (new dataModel.dataTemplate());
}
};
dataModel.collectedNotes();
ko.applyBindings(dataModel);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<form data-bind="foreach: trialData">
<input type="text" name="name" data-bind="textInput: myData"><br>
</form>
<button data-bind="click:saveToLocalStorage">Save To local storage</button>

Knockout observableArray not being populated by inherited datepicker value

I am having trouble populating an observableArray with a value inherited from a datepicker. I have a disabled textbox that displays the value of the datepicker as part of the data collection section. As it is disabled and not being typed in, it is not updating the observableArray.
I have created an example jsfiddle where I have stripped down and localised the problem.
Any help getting the value to appear in the observableArray would be great as I am really struggling to figure this one out!
HTML
<!--Date Load -->
<span><b>Select a date:</b></span>
<span><input id="theDate" data-bind="datepicker: viewModelWardStaff.dateMonthYear, datepickerOptions: { dateFormat: 'dd/mm/yy' } "></span>
<!--Input Form -->
<span><h4>Input New Entries</h4></span>
<div style="border: solid 1px;" data-bind="with: viewModelWardStaff">
<form class="grid-form" id="dataCollection">
<fieldset>
<div data-row-span="1">
<div data-field-span="1">
<label>Date</label>
<input id="cDate" class="autosend" data-bind="textInput: dateMonthYear, enable: false">
</div>
<div data-field-span="1">
<label>Status</label>
<input id="cStatus" maxlength="200" class="autosend" data-bind="textInput: wardstaff.Status" type="text">
</div>
</div>
</fieldset>
<div style="margin: 5px;">
<a style="margin-left: 300px;" id="addFileButton" class="button-link" data-bind="click: viewModelWardStaff.addEntry">Add</a>
</div>
</form>
</div>
<h4>View Model Ward Staff</h4>
<div data-bind="with: viewModelWardStaff">
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
</div>
KnockoutJS
moment.locale('en-gb');
function WardStaff(data) {
var self = this;
self.Date = ko.observable(data.Date());
self.Status = ko.observable(data.Status());
};
function oWardStaff() {
var self = this;
self.Date = ko.observable();
self.Status = ko.observable();
};
var viewModelWardStaff = function () {
var self = this;
self.wardstaff = new oWardStaff();
self.dateMonthYear = ko.observable();
self.entries = ko.observableArray([]);
self.addEntry = function () {
self.entries.push(new WardStaff(self.wardstaff));
}
self.removeEntry = function (entry) {
self.entries.remove(entry);
}
};
// dateString knockout
ko.bindingHandlers.dateString = {
update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
var value = valueAccessor(),
allBindings = allBindingsAccessor();
var valueUnwrapped = ko.utils.unwrapObservable(value);
var pattern = allBindings.datePattern || 'YYYY-MM-DD HH:mm:ss';
if (valueUnwrapped == undefined || valueUnwrapped == null) {
$(element).text("");
}
else {
var date = moment(valueUnwrapped, "YYYY-MM-DDTHH:mm:ss"); //new Date(Date.fromISO(valueUnwrapped));
$(element).text(moment(date).format(pattern));
}
}
}
//datepicker knockout
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//WORK
//handle the field changing
ko.utils.registerEventHandler(element, "change", function () {
var observable = valueAccessor();
if (moment($(element).datepicker("getDate")).local().format('YYYY-MM-DD') == 'Invalid date') {
observable(null);
}
else {
observable(moment($(element).datepicker("getDate")).local().format('YYYY-MM-DD'));
}
});
//handle disposal (if KO removes by the template binding)
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).datepicker("destroy");
});
},
//update the control when the view model changes
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
current = $(element).datepicker("getDate");
if (moment(value).format('DD/MM/YYYY') == 'Invalid date') {
$(element).datepicker("setDate", null);
}
}
};
// Master View Model
var masterVM = function () {
var self = this;
self.viewModelWardStaff = new viewModelWardStaff();
};
// Activate Knockout
ko.applyBindings(masterVM);
I think the problem is that your observable date, dateMonthYear, lives in your master view model. The Date property of self.wardstaff is never set.
You could solve this by sharing the observable in your master view model with the one in the wardstaff property:
function oWardStaff(obsDate) {
var self = this;
self.Date = obsDate;
self.Status = ko.observable();
};
/* ... */
self.dateMonthYear = ko.observable();
self.wardstaff = new oWardStaff(self.dateMonthYear);
Now, whenever you pick a new date, it writes it to the observable referenced by both viewmodels.
This line suddenly becomes useful:
function WardStaff(data) {
var self = this;
self.Date = ko.observable(data.Date()); // <-- here
self.Status = ko.observable(data.Status());
};
since Date is now actually set.
Fiddle that I think now works correctly: https://jsfiddle.net/n0t91sra/
(let me know if I missed some other desired behavior)

knockout mvvm binding with metro.js datepicker

I was trying to hack my way around with the metro.js datepicker and knockout. So far my datepicker binding code looks like:
ko.bindingHandlers.datepicker = {
init: function(el, va, ba, model, ctx) {
var prop = va();
$(el).datepicker({
onSelect: function(txt, date) {
prop(date);
}
});
},
update: function(el, va, ba, model, ctx) {
var prop = va();
var date = ko.unwrap(prop);
if(date) {
applyDate(date);
}
function applyDate(dt) {
var j = $(el);
var dp = j.data('datepicker');
var inp = j.find('input');
var fmt = dp.options.format;
var sDate = format(fmt, dt);
// dp._calendar.calendar.dayClick(sDate, dt);
// inp.value = sDate;
dp._calendar.calendar('setDate', sDate);
j.find('input').val(dp._calendar.calendar('getDate')).trigger('change', sDate);
}
function format(fmt, dt) {
fmt = fmt.replace('yyyy', dt.getFullYear());
fmt = fmt.replace('mm', pad(dt.getMonth() + 1));
fmt = fmt.replace('dd', pad(dt.getDate()));
return fmt;
}
function pad(n) {
return parseInt(n) < 10 ? '0' + n: '' + n;
};
}
}
Issue is that when I issue a model update on the date property its bound to the datepicker doesn't update. I mean, it does it the very first time, but post that, it fails to update the textbox; calendar shows okay however. Ultimately I need to change the logic in the applyDate function...
JSBin: http://jsbin.com/rupaqolexa/1/edit?html,js,output
Update: Another issue just cropped up...it doesn't work in IE 10+. The date appears as NaN in the UI...
Update: Steps for reproduction
type date 2nd text box: 2013/05/13 & click on the Change button. Observe date is updated in the datepicker textbox. This works as expected. (Except in IE).
type another date in the textbox & click the change button. Observe the date is not updated in the datepicker textbox. Expected here that the datepicker textbox updates with latest value.
In the update part of your custom binding you need to make all the changes to the bound elements, which include the calendar widget, and the related input element.
I've modified the code to do so, so that it now works.
function ViewModel(date) {
var model = this;
model.date = ko.observable(date);
model.set = function() {
var val = $('#somedate').val();
var dt = new Date(val);
model.date(dt);
};
}
ko.bindingHandlers.datepicker = {
init: function(el, va, ba, model, ctx) {
var prop = va();
$(el).datepicker({
onSelect: function(txt, date) {
prop(date);
}
});
},
update: function(el, va, ba, model, ctx) {
var newDate = ko.unwrap(va());
if(newDate) {
var $el = $(el);
var datePicker = $el.data('datepicker');
var $input = $el.find('input');
var formattedDate = format(datePicker.options.format, newDate);
datePicker._calendar.calendar('setDate', formattedDate);
$input.val(formattedDate);
//$input.val(dp._calendar.calendar('getDate'))
// .trigger('change', sDate);
}
function format(fmt, dt) {
fmt = fmt.replace('yyyy', dt.getFullYear());
fmt = fmt.replace('mm', pad(dt.getMonth() + 1));
fmt = fmt.replace('dd', pad(dt.getDate()));
return fmt;
}
function pad(n) {
return parseInt(n) < 10 ? '0' + n: '' + n;
}
}
};
var m = new ViewModel();
$(function(){
ko.applyBindings(m);
});
<link href="//metroui.org.ua/css/metro.css" rel="stylesheet">
<link href="//metroui.org.ua/css/metro-icons.css" rel="stylesheet">
<link href="//metroui.org.ua/css/metro-responsive.css" rel="stylesheet">
<link href="http://metroui.org.ua/css/metro-schemes.css" rel="stylesheet">
<script src="http://metroui.org.ua/js/jquery-2.1.3.min.js"></script>
<script src="http://metroui.org.ua/js/metro.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.3.0/knockout-debug.js"></script>
<div>
<div class="input-control text" data-bind="datepicker: date">
<input type="text">
<button class="button"><span class="mif-calendar"></span></button>
</div>
</div>
<div>
<label>Date</label>
<div class="input-control text">
<input type="text" id="somedate"/>
</div>
<input type="button" class="button" value="Change" data-bind="click: set"/>
</div>
<div>
<code data-bind="text: date"></code>
</div>
However there is still a little hiccup: the datepiceker's calendar setdate adss new selected date, instead of replacing selected ones. Please, see the API docs to solve this yourself.

Angular edit a copy of a copy

I'm having a few problems editing a copy of a copy.
When you first edit a record it is assigned to a $scope.original and a copy is taken for editing and stored in $scope.copy which can be changed and saved back to $scope.original which in-turn updates $scope.something correctly.
The problem is while editing the first record if you then take a copy of one of the values for further editing, it doesn't get updated when the $scope.saveSomething() function is called.
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.Something = [{
name: "Aye",
desc: new Date()
}, {
name: "Bee",
desc: new Date()
}, {
name: "See",
desc: new Date()
}];
//=================== First copy
$scope.edit = function(what) {
$scope.original = what;
$scope.copy = angular.copy(what);
}
$scope.save = function(copy) {
angular.copy($scope.copy, $scope.original);
$scope.cancel();
}
$scope.cancel = function() {
$scope.copy = null;
}
//=================== Second copy
$scope.editName = function(what) {
$scope.originalName = what;
$scope.copyName = angular.copy(what);
}
$scope.saveName = function() {
angular.copy($scope.copyName, $scope.originalName);
$scope.cancelName();
}
$scope.cancelName = function() {
$scope.copyName = null;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="MyCtrl">
<div ng-repeat="s in Something">
<pre>{{s | json}}</pre>
<a ng-click='edit(s)'>edit</a>
<br/>
<br/>
</div>
<input type='text' ng-model='copy.name' />
<input type='text' ng-model='copy.desc' />
<br/>
<button ng-click='save(copy)' ng-disabled="!copy">save</button>
<button ng-click='cancel()' ng-disabled="!copy">cancel</button>
<a ng-click='editName(copy.name)'>edit name</a>
<br>
<br>
<input type='text' ng-model='copyName' />
<br>
<button ng-click='saveName()' ng-disabled="!originalName">saveName</button>
<button ng-click='cancelName()' ng-disabled="!originalName">cancelName</button>
</div>
</div>
I'm fairly new to Angular, and have been scratching my head on this one for a while now, any ideas why?
Edit
Updated the code to give a better example, the first version suggested that you might know which value of the first edit's values you were editing, and the solution scarlz posted ( http://jsfiddle.net/Karl33to/w23ppp9r/ ) just sets that value directly in the second save function, but I need to be able to do the second edit on any of the values that the first edit loads.
Have also created a fiddle if that's easier for you to run / fork http://jsfiddle.net/w23ppp9r/2/
Your problem arises from your use of angular.copy. In $scope.saveName, your destination $scope.originalName is a string, which will result in angular throwing an error.
There is actually no reason to use angular.copy at all if you're working with primitives. Instead, you could use the following here:
$scope.editName = function(what) {
$scope.originalName = what;
$scope.copyName = what;
};
$scope.saveName = function() {
$scope.copy.name = $scope.copyName;
$scope.cancelName();
}
I've managed to come up with a simple solution, which seems to work.
Instead of passing the primitive to the second edit function, if I pass in the key and a copy of the object instead, I can then update the first copy correctly.
Here's a working fiddle http://jsfiddle.net/w23ppp9r/3/
... and the relevant bit of code:
//=================== Second copy
$scope.editSomething = function(key, obj) {
$scope.originalKey = key;
$scope.originalObj = obj;
$scope.copyVal = obj[key];
};
$scope.saveSomething = function(newVal) {
$scope.originalObj[$scope.originalKey] = newVal;
$scope.cancelEdit();
}
$scope.cancelEdit = function() {
$scope.originalKey = null;
$scope.originalObj = null;
$scope.copyVal = null;
}
Is there a better answer?

knockout binding print function text instead of variable value

I'm writing a small application in JS and I decided to use Knockout.
Everything work well except from a single value that is not printed correctly and I don't understand why.
This is the html view where error appends (viaggio.arrivo is not visualized, and in place of correct value appears a function code like this "function c(){if(0 <arguments.length){if ..." and so on)
<input data-bind="value: viaggio.arrivo" />
And this is the javascript View Model.
Code is pretty long so I put it in a jsFiddle.
function ViewModel() {
function Viaggiatore(nome, cognome, eta, citta) {
var self = this;
self.nome = nome; self.cognome = cognome;
self.eta = ko.observable(eta);
self.citta = ko.observable(citta);
}
function Viaggio(viaggiatore, partenza, arrivo, mete) {
var self = this;
self.viaggiatore = ko.computed(viaggiatore);
self.partenza = ko.computed(partenza);
self.arrivo = ko.observable(arrivo);
self.mete = ko.computed(mete);
}
self.viaggiatore = new Viaggiatore("Mario", "Rossi", 35, "Como");
self.viaggio = new Viaggio(
function(){ return self.viaggiatore.nome+" "+self.viaggiatore.cognome; },
function(){ return self.viaggiatore.citta; },
"Roma",
function(){ return "mete" ;}
);
}
ko.applyBindings(new ViewModel());
I think you need brackets on one of your parameters, like so:
<p data-bind="text: viaggio.partenza()"></p>
Check out the updated fiddle: http://jsfiddle.net/mGDwy/2/

Categories

Resources