Accessing a variable in vuejs or javascript - javascript

I have this javascript variable, I'm using vuejs.
when I try to access an array field to validate a form, the chrome dev tools returns an error.
var checkItems = {contact_email: "", contact_name: "", contact_phone: "", message: "", subject_id: null, …}
I try to access this way:
if(checkItems.contact_email)
alert("email required");
This is the error:
Property or method "contact_email" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option
If the form fields are empty, I want to detect individually which one is empty and send a custom error for each one, for example:
Name field is empty
The email field is empty
This is my vuejs code:
var locale = '{{ $lang }}'; //'es-ES',
var V_Alerts = new Vue({
el : '#v-alerts',
data : {
types : ['danger', 'warning', 'success', 'info'],
alerts : [
]
},
methods : {
add : function(type, content, opts)
{
this.alerts.push({
type : type,
content : content,
opts : opts
});
},
addSuccess : function(content, opts){
this.add('success',content, opts)
}
}
});
var new_ticket = new Vue({
el : '#create_ticket',
data : {
uploading : false,
submitting : false,
subject_id : null,
message : '',
errors: [],
},
methods : {
validation: function (params)
{
return {
contact_email : IsEmail(params.contact_email),
contact_name : !!params.contact_name.trim(),
message : !!params.message.trim(),
subject_id : params.subject_id && !!params.subject_id.trim(),
captcha : params.captcha !== 0
}
},
isValid : function(params)
{
var validation = this.validation(params);
return Object.keys(validation).every(function (key) {
return validation[key];
});
},
restart : function()
{
this.uploading = false;
this.submitting = false;
this.subject_id = null;
this.$refs.subjects.restart();
this.$refs.uploads.restart();
$('#message').text('');
$('#order_number').val('');
$('#contact_email').val('');
$('#contact_name').val('');
$('#contact_phone').val('');
$('#message').val('');
grecaptcha.reset();
},
onSubjectSelect : function(subject_id){
this.subject_id = subject_id;
},
_onSubjectsLoaded : function(subjects){
emitOnWidgetContentChanged();
},
createTicket : function(e)
{
var params = {
contact_email : $('#contact_email').val(),
contact_name : $('#contact_name').val(),
contact_phone : $('#contact_phone').val(),
message : $('#message').val(),
subject_id : this.subject_id,
message_files : this.$refs.uploads.completed_ids.join(','),
captcha : grecaptcha.getResponse()
};
#if (Input::has('public_token'))
params.public_token = '{{ Input::get('public_token') }}';
#endif
if ($('#order_number').val() != '')
params.contact_orders = $('#order_number').val();
if (!this.isValid(params))
{
var checkItems = params;
if(checkItems.contact_email)
alert("email");
alert('{{ addslashes(trans('common.empty_or_error_input')) }}');
return;
}
this.submitting = true;
// only ie11 need this manuall
params._token = '{!! csrf_token() !!}';
AjaxServices.post('createTicket', params, function(error, result)
{
this.submitting = false;
if (error)
{
alert('{{ addslashes(trans('accounts/tickets.error_creating_ticket')) }}');
grecaptcha.reset();
}
else
{
alert('#'+ result.ticket_id +' - {{ addslashes(trans('accounts/tickets.new_ticket_created_ok')) }} :)');
V_Alerts.addSuccess('#'+ result.ticket_id +' - {{ addslashes(trans('accounts/tickets.new_ticket_created_ok')) }}');
this.restart();
emitOnWidgetContentChanged();
}
}.bind(this));
},
onUploadComplete : function(ids){
this.uploading = false;
emitOnWidgetContentChanged();
},
onUploadStarted : function(){
this.uploading = true;
setTimeout(emitOnWidgetContentChanged,1);
},
onItemDeleted : function(){
},
onFilesSelected : function(){
}
}
});
function IsEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$(document).ready(function(){
//new_ticket.restart();
});

You are not utilizing Vue properly. The error you are receiving stems from not defining your properties in the data object. You cant just return them as you are in the validation method because Vue is looking for a data object called contact_email, or a method called contact_email() or even a computed property called contact_email.
data : {
// define your properties here
contact_email: '';
},
methods: {
yourMethod: function(){
//modify your properties here
this.contact_email: IsEmail(params.contact_email)
}
}

Related

Value returned by service not update in controller's variable in angularjs

function getList() {
SubCategoryService.getAllList().then(function (response) {
$scope.subCategoryList = response.data;
$scope.subCategoryDetailsList = [];
var subCategoryDetails = [];
for(var i=0; i < $scope.subCategoryList.length; i++) {
var subCategoryListData = $scope.subCategoryList[i];
var subcategory = {
'id' : subCategoryListData.id,
'category' : '',
'name' : subCategoryListData.name,
'created_on' : subCategoryListData.created_on,
'modified_on' : subCategoryListData.modified_on,
'is_deleted' : subCategoryListData.is_deleted,
'is_active' : subCategoryListData.is_active,
'image_name' : subCategoryListData.image_name,
'image_path' : subCategoryListData.image_path
}
CategoryService.getCategoryById(subCategoryListData.category_id).then(function(response1) {
console.log(response1.data);
subcategory.category = response1.data;
}, function(error) {
swal("Error", error.data, "error");
})
subCategoryDetails.push(subcategory);
}
console.log(JSON.stringify(subCategoryDetails));
}, function (error) {
swal("Error", "Something went wrong", "error");
});
}
CategoryService:
this.getCategoryById = function(id) {
return $http({
url: globalUrl.baseurl + 'category/getCategoryById/' + id,
method: 'GET'
})
}
in the above code i am tring to fetch data from CategoryService service and it successfully return the data within the CategoryService.getCategoryById function. Now i am trying to assign returned value by service to subcategory.category which is present in controller. but my problem is it is not updateing the value in subcategory.category.
my guess is:
you are pushing the new variabile inside the array BEFORE the API call is executed (because of the js callback), can you try something like:
CategoryService.getCategoryById(subCategoryListData.category_id)
.then(function(response1) {
console.log(response1.data);
subcategory.category = response1.data;
// PUSHING AFTER API RETURNS THE VALUE
subCategoryDetails.push(subcategory);
}, function(error) {
swal("Error", error.data, "error");
})
// subCategoryDetails.push(subcategory);

How to make it async in javascript or node?

var responseArr = new Array();
async.each(response, function (value, k) {
if(isDateFlag)
{
var defaultValue = value.auction_id;
grpArray.push(value.title);
var postData = {
parent_id : parent_id,
defaultValue : defaultValue,
isDateFlag : isDateFlag,
search_text : search_text
}
getChildNotificationList(postData, function (childArrayData) {
//Creating the response array
responseArr.push({
'notification_id' : childArrayData['notification_id'],
'notification_text' : childArrayData['notification_text']
});
});
}
});
return responseArr;//Blank Array
I want to return the final responseArr after manipulating it from child data query. It return blank array because it does not wait for the query response.
So how it can be async. Thanks
I referred http://justinklemm.com/node-js-async-tutorial/ and https://github.com/caolan/async.
This happens because the control goes on executing the code since javascript is synchronous. For getting the expected result modify the code as below:
var responseArr = new Array();
async.each(response, function (value, k) {
if(isDateFlag){
var defaultValue = value.auction_id;
grpArray.push(value.title);
var postData = {
parent_id : parent_id,
defaultValue : defaultValue,
isDateFlag : isDateFlag,
search_text : search_text
}
getChildNotificationList(postData, function (childArrayData) {
//Creating the response array
responseArr.push({
'notification_id' : childArrayData['notification_id'],
'notification_text' : childArrayData['notification_text']
});
k();
});
} else {
k();
}
}, function (err) {
if (err) {
console.log(err);
} else {
return responseArr;
}
});
The above code is inside a function block. You could get the result by calling the function.
Including the answer using async.map:
async.map(response, function (value, k) {
if(isDateFlag){
var defaultValue = value.auction_id;
grpArray.push(value.title);
var postData = {
parent_id : parent_id,
defaultValue : defaultValue,
isDateFlag : isDateFlag,
search_text : search_text
}
getChildNotificationList(postData, function (childArrayData) {
k(null, {
'notification_id' : childArrayData['notification_id'],
'notification_text' : childArrayData['notification_text']
});
});
} else {
k(null, {
'notification_id' : '',
'notification_text' : ''
});
}
}, function(err, results){
// results is now an array
return results;
});

Meteor, display/sort value by boolean

I'm working on a table in Meteor template, where the is a boolean field "emergency"
I would like to display in the table the cells where there is the "emergency" flag FIRST, and then the others ...
How can I do that please ?
here is the find, I tried to sort(), find and sort inside but It doesn't work .. :/
Template.actionsList.helpers({
actions: function() {
return Actions.find();
}
});
Thanks in advance :)
I get the error: Exception in template helper: TypeError: Cannot read property 'hasOwnProperty' of null
My code is:
Session.set('emergency', false);
Template.actionForm.onRendered(function () {
var $elem = this.$('.emergency');
$elem.checkbox('set ' + (Session.get('emergency') ? 'checked' : 'unchecked'));
$elem.checkbox({
onChange: function () {
Session.set('emergency', !Session.get('emergency'));
}
});
});
Template.actionForm.events({
'submit .new-action': function(event) {
event.preventDefault();
var emergency = Session.get('emergency');
...
Actions.insert({
emergency: emergency
....
Thanks for the help
Use underscore's sortBy() method to sort on objects checking if the 'emergency' field exists via the hasOwnProperty() native method:
Template.actionsList.helpers({
actions: function() {
var actions = Actions.find().fetch();
return _.sortBy(actions, function (a) { return !a.hasOwnProperty('emergency'); });
}
});
Check the demo below.
var actions = [
{
"_id" : "ukn9MLo3hRYEpCCty",
"field" : "foo"
},
{
"_id" : "ukn9MLo3hRYEpCCty",
"field" : "bar",
"emergency": true
},
{
"_id" : "WMHWxeymY4ATWLXjz",
"field" : "abc",
"emergency": false
},
{
"_id" : "5SXRXraariyhRQACe",
"field" : "xyz"
}
];
var result = _.sortBy(actions, function (a) { return !a.hasOwnProperty('emergency'); });
pre.innerHTML = JSON.stringify(result, undefined, 4);
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<pre id="pre"></pre>

How to post a Map with $.ajax

I have a JS function which is supposed to post several Maps that i need in my controller :
var valuesOriginal = new Map();
var valuesEdited = new Map();
var valuesBackup = new Map();
$.each($('#zgImport').serializeArray(), function(i, field) {
if(field.name.substring(0,13) == "userLinesAuto"){
valuesEdited.set(field.name, field.value);
}else if (field.name.substring(0,17) == "userLinesOriginal"){
valuesBackup.set(field.name, field.value);
}else if (field.name.substring(0,9) == "userLines"){
valuesOriginal.set(field.name, field.value);
}
});
$.ajax({
type : 'POST',
url : '<%= importAfterValidationUsers %>',
data : {
original : valuesOriginal,
edited : valuesEdited,
backup : valuesBackup,
formValidationSource : "original"
},
success: function(serverResponse) {
alert("ok");
},
error: function () {
alert("error");
},
timeout: 3000
});
But in my controller my maps are always null
public void importAfterValidationUsers(ResourceRequest request, ResourceResponse response) throws IOException {
Map<String, String[]> users = request.getParameterMap();
Map lala = request.getParameter("original");
}
The request.getParameterMap() contains the "formValidationSource" var but not the map, and request.getParameter("original") returns null.
What do i miss?
Change:
formValidationSource : "original"
TO
"original" : formValidationSource
Edit: Try:
original : JSON.stringify(valuesOriginal)

KO validation: model.errors is undefined

I have this model
var MarketResearch = function (data) {
var self = this;
self.Validate = function() {
if (!self.isValid()) {
self.errors.showAllMessages();
return false;
}
return true;
};
this.id = data ? data.id : 0;
this.city = ko.observable(data ? data.city : '').extend({ required: true });
this.since = ko.observable(data ? data.since : '').extend({ required: true });
this.title = ko.observable(data ? data.title : '').extend({ required: true });
}
Here is the view:
function onDocumentReady() {
koValidationConfig()
// initializeDataPickers(market);
// createCkEditor('market_editor');
ko.applyBindings(market, document.getElementById("market-form"));
}
var market = new MarketResearch(null);
function onSaveMarketClicked() {
market.errors.showAllMessages();
}
function koValidationConfig() {
ko.validation.rules.pattern.message = 'Invalid.';
ko.validation.configure({
// registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
decorateInputElement: true,
});
ko.validation.registerExtenders();
}
I have some required fields here. When I put nothing in the fields it displays "this field is required" and colors the form elements.
But market.errors is always undefined, so I can't check if the form is valid!
market.errors.showAllMessages();
Doesn't work too.
Ko.validation is defined, I checked.
What's wrong?
ko.validation adds an errors property to observables, not models. You also need to use .extend on an observable to enable validation.

Categories