I want to set the time interval for the given function as a variable value as timeInMilliseconds..
but getting error as undefined..please help me to solve this.
Thank you in advance .
window.setInterval(function(){
chrome.storage.local.get("user_inactive_mode", function (obj) {
inactiveStatusMode = obj.user_inactive_mode;
if(inactiveStatusMode == 'true') {
chrome.storage.local.get("user_inactive_time", function (obj) {
var timeInMinuts = obj.user_inactive_time;
var timeInMilliseconds = timeInMinuts * 10;
console.log(timeInMilliseconds);
chrome.idle.queryState(timeInMilliseconds, function (state) {
if (state != "active") {
====
====
=====
}
});
});
}
});
} , timeInMilliseconds);
Initialize the variable timeInMillisecond outside the function.
Reason why it says undefined, is because it's out of scope
var timeInMilliseconds;
window.setInterval(function(){
chrome.storage.local.get("user_inactive_mode", function (obj) {
inactiveStatusMode = obj.user_inactive_mode;
if(inactiveStatusMode == 'true') {
chrome.storage.local.get("user_inactive_time", function (obj) {
var timeInMinuts = obj.user_inactive_time;
timeInMilliseconds = timeInMinuts * 10;
console.log(timeInMilliseconds);
chrome.idle.queryState(timeInMilliseconds, function (state) {
if (state != "active") {
====
====
=====
}
});
});
}
});
} , timeInMilliseconds);
You can read here about the JS scoping: What is the scope of variables in JavaScript?
Related
I am trying to sort some JSON data using Vue. The data gets changed when checking via Vue console debugger, but the actual DOM doesn't get updated.
This is my Vue code:
Array.prototype.unique = function () {
return this.filter(function (value, index, self) {
return self.indexOf(value) === index;
});
};
if (!Array.prototype.last) {
Array.prototype.last = function () {
return this[this.length - 1];
};
};
var vm = new Vue({
el: "#streetleague-news",
data: {
allItems: [],
itemTypes: [],
itemTypesWithHeading: [],
selectedType: "All",
isActive: false,
sortDirection: "newFirst",
paginate: ['sortedItems']
},
created() {
axios.get("/umbraco/api/NewsLibraryApi/getall")
.then(response => {
// JSON responses are automatically parsed.
this.allItems = response.data;
this.itemTypes = this.allItems.filter(function (x) {
return x.Tag != null && x.Tag.length;
}).map(function (x) {
return x.Tag;
}).unique();
});
},
computed: {
isAllActive() {
return this.selectedType === "All";
},
filteredItems: function () {
var _this = this;
return _this.allItems.filter(function (x) {
return _this.selectedType === "All" || x.Tag === _this.selectedType;
});
},
sortedItems: function () {
var _this = this;
var news = _this.filteredItems;
if (_this.sortDirection === 'newFirst') {
news.sort(function (a, b) {
return new Date(b.PostDate) - new Date(a.PostDate);
});
} else {
news.sort(function (a, b) {
return new Date(a.PostDate) - new Date(b.PostDate);
});
}
return news;
}
},
methods: {
onChangePage(sortedItems) {
// update page of items
this.sortedItems = sortedItems;
}
}
});
This is an HTML part:
<paginate class="grid-3 flex" name="sortedItems" :list="sortedItems" :per="12" ref="paginator">
<li class="flex" v-for="item in paginated('sortedItems')">
The bit that seems not to be working is the sortedItems: function () {....
Can anyone see why the DOM is not updating?
The most probable is that sort() method doesn't recognize Date object precedence. Use js timestamp instead:
if (_this.sortDirection === 'newFirst') {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateB.valueOf() - dateA.valueOf();
});
} else {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateA.valueOf() - dateB.valueOf();
});
}
Got there eventually - thanks for your help
sortedItems: function () {
var _this = this;
var news = _this.allItems;
if (_this.sortDirection === 'newFirst') {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateB.valueOf() - dateA.valueOf();
});
} else {
news.sort(function (a, b) {
var dateA = new Date(a.PostDate);
var dateB = new Date(b.PostDate);
return dateA.valueOf() - dateB.valueOf();
})
}
return news.filter(x => {
return _this.selectedType === "All" || x.Tag ===
_this.selectedType;
});
}
How to chain multiple conditions in RethinkDB? This is what I got right now and what works if I only pass live or sports as a parameter. As soon as I pass the live and sports parameter, sports obviously always overwrites the filter variable and the live parameter is ignored.
app.get('/bets', function (req, res) {
var live = req.query.live;
var sports = req.query.sports;
var filter = {};
if (live === undefined) {
filter = r.or(r.row('live').eq(0), r.row('live').eq(1));
} else {
filter.live = parseInt(live);
}
if (sports !== undefined) {
var sports = sports.split(',');
filter = function (doc) {
return r.expr(sports).contains(doc("sport"));
}
}
r.table('bets').filter(filter).limit(100).run(connection, function(err, cursor) {
// ...
});
});
You can chain filters with RethinkDB.
Something along the lines of this (warning, untested) :
app.get('/bets', function (req, res) {
var live = req.query.live;
var sports = req.query.sports;
var liveFilter, sportFilter;
if (live === undefined) {
liveFilter = r.or(r.row('live').eq(0), r.row('live').eq(1));
} else {
liveFilter = function (doc) { return true; };
}
if (sports !== undefined) {
sports = sports.split(','); // no need to redefine the variable here
sportFilter = function (doc) {
return r.expr(sports).contains(doc("sport"));
}
} else {
sportFilter = function (doc) { return true; };
}
r.table('bets')
.filter(liveFilter) // apply the first filter
.filter(sportsFilter) // apply the second filter
.limit(100)
.run(connection, function(err, cursor) {
// ...
});
});
Alternatively you could make one filter function that would handle both the live and sport filters (equally untested, this is to get you started) :
app.get('/bets', function (req, res) {
var live = req.query.live;
var sports = req.query.sports.split(',');
var filter = function(doc){
var sportPass, livePass;
if (live === undefined) {
livePass = r.or(r.row('live').eq(0), r.row('live').eq(1))(doc);
} else {
livePass = parseInt(live); // not sure what you meant by filter.live here
}
if (sports !== undefined) {
sportPass = r.expr(sports).contains(doc("sport"));
}
return sportPass && livePass;
};
r.table('bets').filter(filter).limit(100).run(connection, function(err, cursor) {
// ...
});
});
I'm trying to test that, when the Submit button is clicked on an empty form, all the "please fill in this field" labels are displayed.
I'm doing so with this:
page.click('#btn_submit');
page.expect.element('#validation_label_required').to.be.visible;
where #validation_label_required is represented by the CSS selector:
input[required] ~ p.error-message-required
However, this test passes if ANY of the validation labels are visible. The test should only pass if they ALL are.
How can I achieve this?
You will need to create a custom assertion for that where you locate all elements by selenium commands and then loop to verify condition. It should look something like this
var util = require('util');
exports.assertion = function (elementSelector, expectedValue, msg) {
this.message = msg || util.format('Testing if elements located by "%s" are visible', elementSelector);
this.expected = expectedValue;
this.pass = function (value) {
return value === this.expected;
};
this.value = function (result) {
return result;
};
this.command = function (callback) {
var that = this.api;
this.api.elements('css selector',elementSelector, function (elements) {
elements.value.forEach(function(element){
that.elementIdDisplayed(element.ELEMENT,function(result){
if(!result.value){
callback(false);
}
});
});
callback(true);
});
return this;
};
};
I've just ended up with another custom assertion that check how many elements are visible by given css selector.
/**
* Check how many elements are visible by given css selector.
*
*/
var util = require('util');
exports.assertion = function(elementSelector, expectedCount, msg) {
this.message = msg || util.format('Asserting %s elements located by css selector "%s" are visible', expectedCount, elementSelector);
this.expected = expectedCount;
this.count = 0;
this.pass = function(value) {
return value === this.expected;
};
this.value = function(result) {
return this.count;
};
this.command = function(callback) {
var me = this, elcount = 0;
this.count = 0;
this.api.elements('css selector', elementSelector, function(elements) {
if(elements.value && elements.value.length > 0){
elcount = elements.value.length;
}else{
return callback(false);
}
elements.value.forEach(function(element) {
me.api.elementIdDisplayed(element.ELEMENT, function(result) {
if (result.value) {
me.count++;
}
elcount--;
if (elcount === 0) {
callback(me.count);
}
});
});
});
};
};
I'm looking to add on to the kendoValidator required rule. I want it to function the same way but with one exception. Unfortunately once I provide a function for it in the rules section I have to code all the logic for the required function again.
wondering if there is a way to piggyback off the existing functionality of "required" rule. Currently the code below has everything marked required that isn't disabled, even if it has a value in it.
function runValidation() {
$(".dateTimePickerField").each(function () {
var validator = $(this).kendoValidator({
rules: {
required: function (e) {
if ($(e).is(':disabled'))
{
return true;
}
},
dateValidation: function (e) {
var dateTime = $(e).val();
var currentDate = Date.parse($(e).val());
if (dateTime.length > 0 && !currentDate) {
return false;
}
return true;
}
},
messages: {
//Define your custom validation massages
required: "datetime required",
dateValidation: "Invalid datetime"
}
}).data("kendoValidator");
validator.validate();
});
}
I just ended up coding the necessary logic for the required rule. It wasn't too difficult of a rule to code so i just did that.
function runValidation() {
var boolval = true;
$("input.dateTimePickerField").each(function () {
var validator = $(this).kendoValidator({
rules: {
required: function (e) {
if ($(e).prop('required')) {
if ($(e).is(':disabled') || $(e).val().length > 0) {
return true;
}
return false;
}
return true;
},
dateValidation: function (e) {
var dateTime = $(e).val();
var currentDate = Date.parse($(e).val());
if (dateTime.length > 0 && !currentDate) {
return false;
}
return true;
},
customEventDateValidation: function (e) {
var dateTime = $(e).val();
var currentDate = Date.parse($(e).val());
var row = $(e).closest('tr');
var startDateText = row.find(".startDate").text();
var eventStartDate = Date.parse(startDateText);
if (currentDate && eventStartDate)
{
if(currentDate > eventStartDate)
{
return false;
}
}
return true;
},
customTicketStartDateValidation: function (e) {
if ($(e).hasClass("ticketStartDate"))
{
var dateTime = $(e).val();
var currentDate = Date.parse($(e).val());
var row = $(e).closest('tr');
var ticketEndDateText = row.find("input.ticketEndDate").val();
var ticketEndDate = Date.parse(ticketEndDateText);
if(currentDate && ticketEndDate)
{
if(currentDate > ticketEndDate)
{
return false;
}
}
}
return true;
},
customTicketEndDateValidation: function (e) {
if ($(e).hasClass("ticketEndDate")) {
var dateTime = $(e).val();
var currentDate = Date.parse($(e).val());
var row = $(e).closest('tr');
var ticketStartDateText = row.find("input.ticketStartDate").val();
var ticketStartDate = Date.parse(ticketStartDateText);
if (currentDate && ticketStartDate) {
if (currentDate < ticketStartDate) {
return false;
}
}
}
return true;
}
},
messages: {
required: "Datetime required",
dateValidation: "Invalid datetime",
customEventDateValidation: "Datetime must be before event date",
customTicketStartDateValidation: "Ticket start datetime must be before ticket end datetime",
customTicketEndDateValidation: "Ticket end datetime must be after ticket start datetime"
}
}).data("kendoValidator");
if (!validator.validate()) {
boolval = false;
}
});
return boolval;
}
I tried to define multiple custom validation rules under a observable array, I was referring to https://github.com/ericmbarnard/Knockout-Validation/wiki/Custom-Validation-Rules.
Following is my observablearray with the validation calls:
this.WeeklyData = ko.observableArray([]).extend({
validation: [
{
validator : fminIncrements,
message: 'use 15 min increments'
},
{
validator: ValidateMinMax,
message: "Invalid min/max value"
}
]
});
var ValidateMinMax = function (valueArray) {
var check = true;
ko.utils.arrayFirst(valueArray, function (value) {
if (parseInt(value.Val(), 10) < 0 || parseInt(value.Val(), 10) > 168) {
check = false;
return true;
}
});
return check;
};
var fminIncrements = function (valueArray) {
var check = true;
ko.utils.arrayFirst(valueArray, function (value) {
if (parseInt(value.Val(), 10) % 15 !== 0) {
check = false;
return true;
}
});
return check;
};
when I do this only the first rule fires. I debugged, and it doesn't even hit the second one. Any idea?
Thanks in advance for any help.
I believe its because you are using the ko.utils.arrayFirst(). If you use the ko.utils.arrayForEach() instead to check for every case then it shouldn't return at the first occurrence.