I need to create a isDone for my ToDoList and it should return true or false if it's done or not. But if the isDone date is set it should throw an Error since it should be a "read-only". I was thinking something like:
function ToDoItem(isDone) {
let _isDone;
Object.defineProperty(this, 'isDone', {
get: function() {
return _isDone;
}
});
}
But how do I continue so the value returned is true or false?
In my finishedDate I did this:
Object.defineProperty(this, 'finishedDate', {
get: function() {
return _finishedDate;
},
set: function(finishedDate) {
if (finishedDate !== undefined && Object.prototype.toString.call(finishedDate) !== '[object Date]') {
throw new TypeError('invalid date');
}
_finishedDate = finishedDate;
}
});
Thats not a functional function for what you want is it? I would have guess something simple like the following philosophy
function isDone(item) {
return todoList.getItem(item).status;
}
Related
I have LIVR in a project i'm working now and is quite unclear to me how this work. I can't understand how to create new rules for custom validation.
Here's the code:
LIVR.Validator.defaultAutoTrim(true);
let validator = new LIVR.Validator({});
LIVR.Validator.registerDefaultRules({
nested_object_value() {
return function (value) {
if (!value || (value && !value.value || value === [])) {
return 'REQUIRED';
}
return '';
};
},
max_number_advancement() {
return function (value) {
if (value > 100) {
return 'MAX_NUMBER';
}
return '';
};
},
required_if_activity_present() {
return function (value, allValue) {
if (allValue.activitycycletype && !value || allValue.requestpeople === []) {
console.log(first)
return 'REQUIRED_IF_CYCLETYPE';
}
return '';
};
},
});
And this is how its used:
validationForm = () => {
const { formValue, updateErrors } = this.props;
const validData = validator.validate(formValue);
console.log(formValue)
if (!validData) {
const errorsValidator = validator.getErrors();
if (errorsValidator && Object.keys(errorsValidator).length > 0) {
const newErrors = {};
Object.keys(errorsValidator).forEach((error) => {
newErrors[error] = errorsValidator[error];
});
updateErrors(newErrors);
}
blame(t('validation-error'));
return false;
}
updateErrors({});
return true;
}
Opening the form with this validation in the app, seems to call only the last method required_if_activity_present().
What i expect here is that i can create a new method inside registerDefaultRules(), that is a LIVR method, like this:
LIVR.Validator.registerDefaultRules({
re quired_not_empty() {
return function (value) {
if (!value) {
return 'REQUIRED';
}
return '';
};
},
... //other methods
}
but seems not working, the newer method is not being called at all by validator.validate()
Anyone know how to create a new rules where i can check if an element inside the object that has to be validate is an empty array?
Because seems that LIVR doesn't return a validation error in this case, but only on empty string and null values.
Thanks in advance
I am retrieving data from the Vuex Store. I first of all want to check of the array is present in the Vuex Store, after that I want to check if the noProducts object at index 0 is not present.
The reason for this is that tweakwiseSortedProducts is used for both products and a no Products boolean to react to in the front-end
tweakwiseHasProducts () {
if (this.$store.state.tweakwise?.tweakwiseSortedProducts) {
return (
this.$store.state.tweakwise.tweakwiseSortedProducts[0].noProducts ===
false
);
}
return false;
},
My front-end currently, often, returns:
this.$store.state.tweakwise.tweakwiseSortedProducts[0] is undefined
In the console.
This happens because tweakwiseSortedProducts is not undified but an empty list. You can try:
tweakwiseHasProducts () {
if (this.$store.state.tweakwise?.tweakwiseSortedProducts?.length !== 0) {
return (
this.$store.state.tweakwise.tweakwiseSortedProducts[0].noProducts ===
false
);
}
return false;
},
or just:
tweakwiseHasProducts () {
return this.$store.state.tweakwise?.tweakwiseSortedProducts[0]?.noProducts === false;
},
which will be false if any of this elements is undefined, or true if noProducts is really false
It is recommended to use getter when calling a value in Vuex.
Please refer to the following.
getters: {
getTweakwiseSortedProducts: (state: any) => {
return state.tweakwise?.tweakwiseSortedProducts || [];
},
},
tweakwiseHasProducts () {
this.$store.getters.getTweakwiseSortedProducts.length ? true : false;
}
I have an es6 model that I want to do some basic validation on before it is posted to an endpoint. I wrote a simple isValid() method on the class which I want to return true or false, not truthy, falsey. Since && will return last check which was truthy, I shortcut the function by appending && true to the end of my validation check.
export default class foo {
constructor (data = {}) {
this._id = data.id
this._name = data.name
}
isValid () {
return this._id && this._name && true
}
}
What I want to know is: Is this an appropriate way to return a true value in this context? Is there a better way to do this sort of validation in JS? I realize there are other ways to return a boolean doing 'if' statements, but I wanted this to be fairly concise and thought this might be a valid shortcut...
When you write it like
isValid () {
return this._id && this._name && true
}
it will return true for a truthy value but will not return false for a falsy value.
In order to return true or false, you can use the Boolean constructor function like
isValid () {
return Boolean(this._id && this._name)
}
or else you can make use of ternary operator
isValid () {
return this._id && this._name? true : false
}
Demo snippet:
class foo {
constructor (data = {}) {
this._id = data.id
this._name = data.name
}
isValid () {
return Boolean(this._id && this._name)
}
}
let foo1 = new foo({ id: 1, name: 'abc'});
let foo2 = new foo({ id: 2 });
console.log(foo1.isValid(), foo2.isValid());
You can shorthand !! to cast into boolean.
return !!(this._id && this._name)
I am trying to create a flux store for a React app I am building. I am using an object-assign polyfill npm package and Facebook's Flux library.
Initially I was getting the error "Cannot read property '_data' of null' error in the console which was refering to var currIds = this._data.map(function(m){return m.id;});. That method is currently the only one being called directly. I then did console.log(this) which returned "null".
I find this strange. What is going on?
My code:
var Assign = require('object-assign');
var EventEmitterProto = require('events').EventEmitter.prototype;
var CHANGE_EVENT = 'CHANGE';
var StoreMethods = {
init: function() {},
set: function (arr) {
console.log(this);
var currIds = this._data.map(function(m){return m.id;});
arr.filter(function (item){
return currIds.indexOf(item.id) === -1;
}).forEach(this.add.bind(this));
},
add: function(item){
console.log(this);
this._data.push(item);
},
all: function() {
return this._data;
},
get: function(id){
return this._data.filter(function(item){
return item.cid === id;
})[0];
},
addChangeListener: function(fn) {
this.on(CHANGE_EVENT, fn);
},
removeChangeListener: function(fn) {
this.removeListener(CHANGE_EVENT, fn);
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
bind: function(actionType, actionFn) {
if(this.actions[actionType]){
this.actions[actionType].push(actionFn);
} else {
this.actions[actionType] = [actionFn];
}
}
};
exports.extend = function(methods) {
var store = {
_data: [],
actions: {}
};
Assign(store, EventEmitterProto, StoreMethods, methods);
store.init();
require('../dispatcher').register(function(action){
if(store.actions[action.actionType]){
store.actions[action.actionType].forEach(function(fn){
fn.call(null, action.data);
})
}
});
return store;
};
I can't see where set is called, however your this can be null if the function is invoked through call (see here) or apply, and your first argument is null.
This also happens in your require.register callback:
fn.call(null, action.data) //First parameter is your 'this'.
i have a function that loop all object properties and return value if it qualify certain condition
basically this is how i m doing
//an enum
var BillingType = Object.freeze({
PayMonthly: { key: 'Monthly', value: 1 },
PayYearly: { key: 'Yearly', value: 2 }
});
now to make it work i do this
for (var property in BillingType ) {
if (BillingType .hasOwnProperty(property)) {
if (value === BillingType [property].value) {
return BillingType [property].key;
}
}
}
it works fine but to make it generic for all enums i changed code to
getValue = function (value, object) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (value === object[property].value) {
return object[property].key;
}
}
}
}
now when i try to call from other functions
enumService.getValue(1, 'BillingModel');
rather to loop all properties it start loop on its characters.
how can i convert string to object or m doing it totally wrong . any help will be appreciated
Regards
Your getValue looks fine, just call it using
enumService.getValue(1, BillingModel); // <-- no quotes
and here is a working fiddle: http://jsfiddle.net/LVc6G/
and here is the code of the fiddle:
var BillingType = Object.freeze({
PayMonthly: { key: 'Monthly', value: 1 },
PayYearly: { key: 'Yearly', value: 2 }
});
var getValue = function (value, object) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (value === object[property].value) {
return object[property].key;
}
}
}
};
alert(getValue(1, BillingType));