I'm having trouble using the setter functions on my Sequelize js model properties.
What I want to do is when one property is given a value use that value to populate another property in the table at the same time.
In my model this is the code I have for the property in question...
date_time_paid: {
type:DataTypes.DATE,
set(val) {
const date = new Date(val);
this.setDataValue('date_time_paid', val); // set the the current property
this.setDataValue('month_paid', `${date.getFullYear()}-${(date.getMonth() + 1)}`); //also set another property on the same row
},
},
What I expect to happen is for the date_time_paid column to store the raw value and the month_paid column to store a string derived from it. But when I run my seeder to populate the table with test data the value for the month_paid column remains null.
Is this the correct use of a setter function?
If it is what have I done wrong that means it's not working?
I think you need a just a getter. Forget about date_time_paid and make getter for month_paid:
get month_paid(){
const date = new Date(this.date_time_paid);
return `${date.getFullYear()}-${(date.getMonth() + 1)}`;
}
Related
I am currently learning JavaScript, and have a question about _variable name.
Firstly, what is the relationship between valuable name, and same valuable name with underscore? I am using this._title in getter and setter to get value from title, but I do not understand why _title can be used without declaring, and also when console this._title, it is able to show the value of title.
const movies = [];
const addMovieHandler = () => {
const title = document.getElementById('title').value;
const newMovie = {
info: {
set title(val) {
if(val.trim() === ''){
this._title = 'DEFAULT';
return;
}
this._title = val;
console.log(this)// shows the object of new movie
console.log(val)// show value of title
console.log(this._title)// also show value of title
},
get title() {
return this._title.toUpperCase();
}
}
};
newMovie.info.title = title;//setter
console.log(newMovie.info.title);//getter
movies.push(newMovie);
};
Thank you for your help!
Nagisa
Stepping back a bit, traditionally:
title = 'foo'; // assigns value 'foo' to title (set action)
console.log(title); // references title (get action)
You work directly with title, assigning a value to it directly, and when you reference it, js returns the value of it.
The concept of get and set methods is that you can add a proxy layer to the variable to write your own code to define what happens when you assign something to title (set) or reference it (get). This is most commonly used to add logic for default values or validate/scrub/format values.
So in your code, title and _title are two distinct variables that are not directly/intrinsically tied together, except by your own conventions set within title's set and get methods.
And within set and get, you do whatever you want. In this case, you are using an "internal" variable _title to hold the actual value. This can be named anything you want, but by convention, many people use the same variable name as the public one, but with a _ prefix. You don't even need to have one at all; it just depends on what your goal is.
I have to add a property for an object returned from my db before pushing it to an array. Changing properties work, but adding new ones doesn't. Can anyone can explain the logic behind this behavior?
ids.forEach(async (id, index) => {
//get object without highlight property
let real_a = await database.getA(id)
real_a.highlight = "shoud add highlight property to real_a object"
realItems.push(real_a)
// the correct string is printed
console.log(real_a.highlight)
//object still doesn't have that property
console.log(real_a)
}
It was the intended behavior.Sorry for bothering.
I was using a mongodb query for the database.getA(id) function and it turns out you have to specify a parameter in the mongodb query to get an actual changeable JSON object.
Here is the complete answer:
Why can't you modify the data returned by a Mongoose Query (ex: findById)
I am creating a new Javascript object and passing the values into the constructor I would like the object to have. One value is a moment object (holding a date) I can see that the date is correct (2017-05-09) but the newly constructed object always has the value 2017-05-04. If I do a console.log on the attribute: object.start_date, then I am able to see the correct date, but if I do console.log on object, it shows the moment object with the wrong date 2017-05-04. I've tried updating in the constructor, manually doing an update on the object after creation, or by updating the value within the created object with a new instance function, but nothing changes the date. Here's some code/output.
Main question: Why is the moment object not being updating with the correct value I am giving it?
Thank you.
Function to create new route:
duplicateRouteSuccess(data) {
let route = new Route(data['routeData']);
route.changeStartDate(data['routeData']['starts_at']);
console.log(route);
console.log(route.starts_at);
this.routeCalendar.scheduleRoute(route, route.repeats);
this.close();
}
and the constructor:
constructor (data) {
this.id = data['id'];
this.name = data['name'];
this.starts_at = moment(data['starts_at']);
this.repeats = data['repeats'];
this.repeat_rate = data['repeat_rate'];
}
UPDATE
doing JSON.stringify to my objects did show that they both have the same date, of 2017-05-08. But then my question is "when I access the attribute object.start_date to set the object onto a calendar, why does object.start_date say 2017-05-04"? Here is the stringify output image:
UPDATE 2
The route.changeStartDate was just an instance function I created to attempt to update the "starts_at" field a second time since it did not appear to be updated in the constructor of the Route class. Here's the code for that:
changeStartDate(start_date){
this.starts_at = moment(start_date)
}
I have a object like as follows
var obj={
userName:sessionStorage["userName"]
}
1st time if I try to access obj.userName i am getting undefined, because there is no value in it.
Now if I am getting undefined even after setting the value for it
sessionStorage["userName"]="name";
obj.userName; //undefined
How to solve this ?
userName takes the value of sessionStorage["userName"] at the time of its creation. Later changes to sessionStorage["userName"] will not be reflected in userName.
If you want to get sessionStorage["userName"] whenever you get value from userName, then you need to define a getter, like this
Object.defineProperties(obj, {
userName: {
get: function() {
return sessionStorage["userName"];
}
}
});
You should do this:
sessionStorage["userName"]="name";
obj.userName = sessionStorage["userName"];
obj.userName;//name
Just changing the value of sessionStorage doesn't reflect the change to the object itself.
In order to change the object, you need to actually change the object.
I have a grid using jqgrid. I need to store the some data returned by the url:, in a local variable so that I can display it in the subgrid. For this I add that column as a hidden column in the main grid, which is of the format in json:
"Details":[{"Name":"ttt", "Quantity":"12"}] .
Then in the loadcomplete: function I save the value to a variable using
var griddata = $("#grid').getCol('Details', false);
Now when I access griddata[0], I get a object Object. I tried to parse it to get the values correctly, but to no avail. I tried:
griddata[0].Details.Name
or
griddata[0].Details.0.Name
or
griddata[0].Name,
but all failed. I guess I am missing the format if the data returned by the getcol() function.I looked up the documentation on the method and it says that it returns just the values when we specify false, but could not get any examples.
If there are any examples or if there are any pointer to the solution, it will be greatly appreciated.
If you check the type of griddata[0] (for example with typeof operator) you will see that it has type of string - this is because the value you are getting is the result of toString() on the object you have passed. The reason for that is the way in which jqGrid is treating values.
If you want to store JSON as the value, you need to stringify it entirely:
"Details": "[{\"Name\":\"ttt\", \"Quantity\":\"12\"}]"
Now you can deserialize those string values into objects like this:
var griddata = $.map($("#grid").jqGrid('getCol', 'Details', false), function(value) {
return JSON.parse(value);
});
After that you can access the objects in the way you want:
var name = griddata[0].Name;
var quantity = griddata[0].Quantity;
As an alternative you can split your object into two columns, so the values can be accessed directly with getCol.