Difference between two datepicker in Backbonejs - backbone.js

Can anyone tell me how to make difference between two datepickers in backbonejs ?
I try to make it like that in my view but it alerts a NAN :
initialize: function () {
this.model.on("change:auprov",function(){
var datedeb = new Date(this.model.get("auprov"));
var dateret = new Date(this.model.get("deprov"));
var diff_ms = dateret.getTime() - datedeb.getTime();
alert(diff_ms/1000/60/60/24);
//this.model.set({"dureeprov": '5'});
},this);
},
Here is a part of my model :
deprov:{
type: "DatePicker",
title: "De (Prov.)",
fieldAttrs:{
className:'col-sm-2 deprov'
},
validators: ["required"]
},
auprov:{
type: "DatePicker",
title: "Au (Prov.)",
fieldAttrs:{
className:'col-sm-2 auprov'
},
validators: ["required"]
},
Regards

Until i cannot know for sure the content and types of this.model.get("auprov") and this.model.get("deprov") i can only make an assumption that these are numbers. Javascript sometimes handle numbers as strings. So to correct it use parseInt to convert string to number.
var datedeb = new Date(parseInt(this.model.get("auprov")));
var dateret = new Date(parseInt(this.model.get("deprov")));

Sorry I was using French datepicker form, so i had to change it to english one, here the correct code :
this.model.on("change:auprov",function(){
var myDateArrayRet = this.model.get("auprov").split("/");
var dateret = new Date(myDateArrayRet[2],myDateArrayRet[1]-1,myDateArrayRet[0]);
var myDateArray = this.model.get("deprov").split("/");
var datedeb = new Date(myDateArray[2],myDateArray[1]-1,myDateArray[0]);
var diff_ms = dateret.getTime() - datedeb.getTime();
alert(Math.ceil(diff_ms / (1000 * 3600 * 24)));
},this);

Related

Backbone fetch (or sync) doesn't look up right url

I'm trying to get some data from the node server, which works fine, but when I try to GET data via the Backbone fetch (or sync), the request fails. I noticed that, for some reason, actual request is wrong: 'GET http://localhost:3000/socket.io/1/' where it should be 'GET http://localhost:3000/cars', since '/cars' is the value of the URL field that Backbone uses by convention for these operations. These are the relevant modules:
var Backbone = require("backbone");
var Car = require('models/car');
var Cars = Backbone.Collection.extend ({
model: Car,
url: '/cars',
// Unselect all Car Cards
resetSelected: function() {
for (var i=1; i<=this.length; ++i) {
var carcard=this.get(i);
carcard.set({"selected": false});
console.log(carcard.attributes.name + ' unselected');
}
},
// Select a specific model from the collection
selectByID: function(id) {
this.resetSelected();
var carcard = this.get(id);
carcard.set({"selected": true});
console.log(carcard.attributes.name + " selected");
return carcard.attributes.id;
}
});
module.exports = Cars;
And a model:
var Backbone = require("backbone");
var Car = Backbone.Model.extend({
defaults: {
year: 2011,
brand: "Brand",
model: "Model",
name: "Car Name",
pictureFle: "img/car.jpg",
kmTraveled: 0,
litresSpent: 0,
selected: false
},
});
module.exports = Car;
I tried to populate the collection like this:
var cars = new Cars();
cars.fetch();
but, as I explained, failed. Any ideas what the problem could be?

BackboneJS How to merge collections

I asked this before BackboneJS Display multiple collections in one <ul>-Element but I can't get it to work and I'm starting getting really desperate so
how can I merge these 3 collections and display them in the same <ul>?
define(['app','backbone','modules/artistInstagram', 'modules/artistTwitter',
'modules/artistFacebook'
], function (App, Backbone, ArtistInstagram, ArtistTwitter, ArtistFacebook) {
var ArtistSocialMedia = App.module();
ArtistSocialMedia.View = Backbone.View.extend({
tagName: 'ul',
id: 'suptiles',
beforeRender: function(){
var artistinstagramCollection = new ArtistInstagram.ArtistInstagramCollection();
artistinstagramCollection.artist_id = this.artist_id;
this.insertView('.socialMedia', new ArtistInstagram.View({collection: artistinstagramCollection}));
artistinstagramCollection.fetch();
var artisttwitterCollection = new ArtistTwitter.ArtistTwitterCollection();
artisttwitterCollection.artist_id = this.artist_id;
this.insertView('.socialMedia', new ArtistTwitter.View({collection: artisttwitterCollection}));
artisttwitterCollection.fetch();
var artistfacebookCollection = new ArtistFacebook.ArtistFacebookCollection();
artistfacebookCollection.artist_id = this.artist_id;
this.insertView('.socialMedia', new ArtistFacebook.View({collection: artistfacebookCollection}));
artistfacebookCollection.fetch();
}
});
return ArtistSocialMedia;
});
Right now, it clearly creates 3 views but I want to merge them into one collection. Please help!
Thanks in advance...
Don't overthink it - since you're defining an element with dynamic content, it should be its own View. It's an unordered list, so the tag name must be <ul>. All you're doing is filling in the <li>'s, so the template isn't very complicated.
var collection1 = new WhateverCollection();
var collection2 = new WhateverCollection();
var collection3 = new WhateverCollection();
var ListView = Backbone.View.extend({
tagName: 'ul',
render: function(){
// define template
var templateStr = '<% _.each(collection,function(model){ %>\
<li><%- model.name %></li>\
<% }); %>';
// convert to function
var template = _.template(templateStr);
// for learning purposes, render each one individually
var htmlFromFirst = template({ collection: collection1.toJSON() });
var htmlFromSecond = template({ collection: collection2.toJSON() });
var htmlFromThird = template({ collection: collection3.toJSON() });
// set the html
this.$el.html( htmlFromFirst + htmlFromSecond + htmlFromThird );
return this;
}
});

How to sort collections in backboneJs

im learning BackboneJs using the documentation and a book called "Beginning backbone".
But I have been stuck at the sorting collections part for hours.
Also tried to research but I find the results complicated =/
I know I have to use the comparator, as shown in the documentation but I don't understand how to apply it to the current code syntax-wise
http://backbonejs.org/#Collection-comparator
var Book = Backbone.Model.extend({
defaults:
{
title: "default title",
author: "default author",
pages: 20
},
comparator: function(item)
{
//sort by title
return item.get('title');
}
});
var book1 = new Book({ title:"Book of wonders",author:"author1",pages:1 });
var book2 = new Book({ title:"Zelda",author:"author2",pages:2 });
var book3 = new Book({ title: "Drake's out", author: "author3",pages:3});
var book4 = new Book({ title: "AutoCad",author: "author4",pages: 4});
var Library = Backbone.Collection.extend({
model: Book
});
var library = new Library([book1,book2]);
library.add([book3,book4]);
library.forEach(function(model){
console.log('Book is called '+model.get("title"));
});
console.log('Library contains '+library.length+' books');
This is a working solution, it will sort everything by title.
to sort it by anything else just change the parameter of the get function inside the comparator function
var Book = Backbone.Model.extend({
defaults:
{
title: "default title",
author: "default author",
pages: 20
}
});
var book1 = new Book({ title:"Book of wonders",author:"author1",pages:1 });
var book2 = new Book({ title:"Zelda",author:"author2",pages:2 });
var book3 = new Book({ title: "Drake's out", author: "author3",pages:3});
var book4 = new Book({ title: "AutoCad",author: "author4",pages: 4});
var Library = Backbone.Collection.extend({
model: Book,
initialize: function()
{
console.log("new collection");
},
comparator: function(a,b)
{
//sort by title
return a.get('title') < b.get('title') ? -1 : 1;
}
});
var library = new Library([book1,book2]);
library.add([book3,book4]);
library.sort();
library.forEach(function(model){
console.log('Book is called '+model.get("title"));
});
console.log('Library contains '+library.length+' books');

Accessing AngularJS variable in slickgrid

I have integrated SlickGrid with my Angular JS application. Earlier I was populating the Grid Data with plain hardcoded javascript code[see below]. But now I need to get the grid data from REST service which is invoked in my angular Js Controller and saved in an object array. How do I access a variable[array] defined in angular js inside my SlickGrid javascript code.
I tried replacing 'data' below with the array defined in angular js code but it's not working. Can anyone please help me here.
$(function () {
/* need to comment out this code once I can use the array defined in angular Js */
var data = [];
for (var i = 0; i < 500; i++) {
data[i] = {
title: "Task " + i,
duration: "5 days",
percentComplete: Math.round(Math.random() * 100),
start: "01/01/2009",
finish: "01/05/2009",
effortDriven: (i % 5 == 0)
};
}
grid = new Slick.Grid("#myGrid", data, columns, options);
})
Update: This is my slickgrid code. I am invoking a REST service to get the data in $scope.data1 and then using it to populate the slickgrid but I am getting an empty slickgrid. But if I hardcode the data in $scope.data1 , it works. What I am missing? Can anyone please help me. I have spent an entire day on this issue.
$scope.populateGridData = function()
FetchPopulation.get({id:1} , function(response ) {
$scope.data1 = [];
for (var i = 0; i < response.PopulationList.population.length; i++)
$scope.data1[i] = {
firstName: response.PopulationList.population[i].firstName,
lastName: response.PopulationList.population[i].lastName,
designation: response.PopulationList.population[i].designation,
department: response.PopulationList.population[i].department,
salary: response.PopulationList.population[i].salary,
rating: response.PopulationList.population[i].rating,
joiningDate: response.PopulationList.population[i].joiningDate,
employeeId: response.PopulationList.population[i].employeeId,
employeeType: response.PopulationList.population[i].employeeType,
manager: response.PopulationList.population[i].manager,
permanent: (i % 5 == 0),
percentComplete: Math.round(Math.random() * 100)
};
/*
$scope.data1= [{employeeId:"12345", firstName: "aaa", lastName: "bbb" , designation:"Business Analyst" , department:"FSI" ,
salary:"120000",rating:"1" , joiningDate:"12/8/2013" , employeeType:"permanent" , manager:"aaaa" }];
*/
var grid = new Slick.Grid("#myGrid", $scope.data1, $scope.columns, $scope.options);
$scope.grid.setSelectionModel(new Slick.CellSelectionModel());
});
};
Did you type by hand the commented line there? Because it's not valid JSON, everything has to be escape [{employeeId:"12345" should be [{"employeeId":"12345",... and even if it's not that, your dataset seems wrong. I am not using SlickGrid without the DataView as you are doing but if you take the basic example and copy this piece of code (pulled from SlickGrid example2:
$(function () {
for (var i = 0; i < 5; i++) {
var d = (data[i] = {});
d["title"] = "<a href='#' tabindex='0'>Task</a> " + i;
d["duration"] = "5 days";
d["percentComplete"] = Math.min(100, Math.round(Math.random() * 110));
d["start"] = "01/01/2009";
d["finish"] = "01/05/2009";
d["effortDriven"] = (i % 5 == 0);
}
grid = new Slick.Grid("#myGrid", data, columns, options);
})
it will most probably work... Try this piece out before going back to your code, but I strongly suspect your JSON result might not be valid as you think it is... now after you tried the basic sample and you go back to your code, you could try to validate your JSON output by going here: JSONLint just copy+paste your JSON in there and click validate.

DisplayField - How to format for date?

I need to display a read only view of data. I've chosen the DisplayField component to do this. My problem is that I would like an easy way to call BasicForm.setValues(values) and have a date string automagically render correctly in one of the displayFields. I haven't found anything that will do this for me (e.g. a renderer function), and am about to just format the date string manually prior to calling setValues(values). Is there some slick way to do this?
Thanks!
Ok if you are using a direct form load then you need to listen for the form's BasicForm 'actioncomplete' event. When this event fires the handler is supplied two arguments. The first is the BasicForm and the second argument is an Ext.form.Action object. We are specifically looking for an Ext.form.Action.Load object. From here we get access to the action's result.data object and we can massage the data values before this handler returns and the values are loaded into the form.
function fmtDate(sf, rec) {
if ( rec[sf] ) {
var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('l j F Y');
}
};
myForm.getForm().on({
actioncomplete: function(form, action) {
if (action.type === 'load') {
if (action.result.success) {
var data = action.result.data;
data.someFormattedDate = fmtDate('myDateTS', data);
} else {
//handle an error here
}
}
}
});
Now all you need in your form is a displayField named 'someFormattedDate' and Bob's your uncle (Aussie slang for it's all good). You can also achieve exactly the same thing by providing a 'success:' function to your myForm.getForm().load() call. See the ExtJS docs for Ext.form.Action.Load.
Cheers, t00bs.
I ended up subclassing displayField. That seems to work best, but I wish there was an out-of-the-box fix for something as basic as displaying a formatted date. This is my first pass at it, so it is just an example.
FormattableDisplayField = Ext.extend(Ext.form.DisplayField, {
constructor:function(config) {
var config = config || {};
Ext.applyIf(config, {
dateFormat:'c',
type:null,
displayFormat:'M d, Y'
});
FormattableDisplayField.superclass.constructor.call(this, config);
},
setValue: function(value) {
if (! this.type) {
FormattableDisplayField.superclass.setValue(value);
}
else if (this.type == 'date') {
var parsedDate = Date.parseDate(value, this.dateFormat);
if (Ext.isDate(parsedDate)) {
this.setRawValue(parsedDate.format(this.displayFormat));
}
else {
this.setRawValue(value);
}
}
else if (this.formatter) {
var formattedValue = this.formatter(value);
this.setRawValue(formattedValue);
}
}
});Ext.reg('formattabledisplayfield', FormattableDisplayField);
I came across this same problem because I like to pass my dates around as Unix timestamps and I had a requirement to display them using various formats depending on context. Here's how I did it.
If you are loading the data via a store then you can use the convert function provided by Ext.data.Field. For example:
var fields = [
{name: 'sysTestedDateObj', mapping: 'sysTestedDateTS', type: 'date', dateFormat: 'timestamp'},
/** Converted Fields **/
{name: 'sysTestedDate', convert: function(v, rec){
return fmtDate('sysTestedDateTS', rec);
}},
{name: 'targetChangeStartDate', convert: function(v, rec){
return fmtDate('targetChangeStartDateTS', rec);
}},
{name: 'createDateTime', convert: function(v, rec){
return fmtDateTime('createDateTS', rec);
}},
{name: 'modifyDateTime', convert: function(v, rec){
return fmtDateTime('modifyDateTS', rec);
}},
];
var store = new Ext.data.JsonStore({
...
fields: fields
});
Here's some conversion functions:
function fmtDate(sf, rec) {
if ( rec[sf] ) {
var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('l j F Y');
}
};
function fmtDateShort(sf, rec) {
if ( rec[sf] ) {
var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('D j M Y');
}
};
function fmtDateTime(sf, rec) {
if ( rec[sf] ) {
var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('l j F Y h:i a');
}
};
function fmtDateTimeShort(sf, rec) {
if ( rec[sf] ) {
var dt = new Date(); dt.setTime(rec[sf] * 1000); return dt.format('D j M Y h:i a');
}
};
Where sf is the source field we are deriving the formatted date string from.
Note the following, it's important. The convert() function is presented with a copy of the data record as read by the reader (this is in the ExtJS docs). This means you can't use any mapped fields in your conversions. In the fields array above I have a field defined as,
{name: 'sysTestedDateObj', mapping: 'sysTestedDateTS', type: 'date', dateFormat: 'timestamp'}
So I'm creating the sysTestedDateObj date object from the sysTestedDateTS field and I've told the reader that I want it to give me a date object derived from an object containing a Unix timestamp. This is a nice object to have for later on but it won't be part of the data record passed to our conversion function.
Also note that a conversion function can reference fields in the record that are not defined for use by the store. In the example above I an using the field sysTestedDateTS in a conversion function because I know the server is supplying it in it's JSON response, yet because I haven't defined it in the fields array it won't be available via the store to the consuming component.
http://dev.sencha.com/deploy/dev/docs/?class=Ext.util.Format
I think dateRenderer is the renderer function that you are looking for?
Ext.form.field.Display.html#cfg-renderer
A function to transform the raw value for display in the field.
Ext.Date.html#method-format
Formats a date given the supplied format string.
var data = {
"OrderNo": "2017071200000246",
"Createtime": "2017/7/12 13:16:42"
}; // your read only data; or use bind store
var form = Ext.create({
xtype: 'form',
defaultType: 'displayfield',
defaults: {
labelWidth: 120,
labelSeparator: ':'
},
items: [
{ fieldLabel: 'Order Number', value: data.OrderNo },
{ fieldLabel: 'Create Time', value: data.Createtime,
renderer: function (value, field) {
var date = new Date(value);
var newVal = Ext.Date.format(date, 'Y-m-d H:i:s');
return newVal;
}
}
]
});

Resources