React-notification-system - trigger notification on JSON input - javascript

Using react-notification-system, I am attempting to create a pop-up notification each time a JSON array is returned from the backend. For the sake of showing the issue I've manually added the array and parsed it in the below code.
As it appears I wish to trigger the event if the "type" of the alerts array is either "WARNING" or "ERROR", and furthermore print the message that comes along with it in the "message" part.
I'm pretty sure the issue I have is with the state and props. Right now, running this code, I am getting Uncaught TypeError: Cannot read property 'type' of undefined - Which leads me to the question, how do I access the information inside the array in React properly, and trigger it in the return function on the conditions?
Sample code:
var NotificationSystem = React.createClass({
_notificationSystem: null,
_addNotification: function(event) {
event.preventDefault();
this._notificationSystem.addNotification({
message: 'Danger!',
level: 'error',
position: 'tc'
});
},
componentDidMount: function() {
this._notificationSystem = this.refs.notificationSystem;
},
render: function() {
var mdata = {"alerts":[
{
"dateTime": 111111111,
"message": "This is a super serious warning",
"type": "WARNING"
}
]};
var mdataArr = Object.values(mdata);
console.log(JSON.stringify(mdataArr)); // It prints the JSON in console
if (this.props.mdataArr.type == "WARNING")
this._notificationSystem.addNotification({
message: this.props.mdataArr.message,
level: 'warning',
position: 'tc'
});
else if (this.props.mdataArr.type == "ERROR")
this._notificationSystem.addNotification({
message: this.props.mdataArr.message,
level: 'error',
position: 'tc'
});
return (
<div>
<NotificationSystem ref="notificationSystem" />
</div>
);
}
});

Actually you defined mdataArr in render() method itself, but you are looking for same in this.props
Try this in render method
if (mdataArr[0].type == "WARNING")
this._notificationSystem.addNotification({
message: mdataArr[0].message,
level: 'warning',
position: 'tc'
});
else if (mdataArr[0].type == "ERROR")
this._notificationSystem.addNotification({
message: mdataArr[0].message,
level: 'error',
position: 'tc'
});

Related

how to call jquery pnotify only once during web form

Hello i am trying to call pnotify in my asp.net web form. It is running properly but when i refresh my page it show me that same notify again...
So anyone can please help me from this issue and here is my code:
function successMessage() {
new PNotify({
title: "Success",
text: "Login Successfully",
width: "100%",
timeout:'100',
cornerclass: "no-border-radius",
addclass: "stack-custom-top bg-primary",
type: 'success',
});
}
You can add loggedIn boolean variable to cooike with false value and then check this variable's value when page is loading. On page loading you must check this value, if it is false then you must call successMessage() and set this variable's value to true else doesn't call the function:
var checkLoggedIn = function(){
var loggedIn = getCooike("loggedIn");
if(!loggedIn){
successMessage();
setCooike("loggedIn", true);
}
}
function successMessage() {
new PNotify({
title: "Success",
text: "Login Successfully",
width: "100%",
timeout:'100',
cornerclass: "no-border-radius",
addclass: "stack-custom-top bg-primary",
type: 'success'
});
}
window.onload = checkLoggedIn;
I wrote getCooike and setCooike methods in my code. You can implement this methods using this article

PreventDefault SweetAlert2

I got this function that override my native js alerts:
function alert(message, title = 'Test', type = 'info')
{
// event.preventDefault();
if(typeof(swal) != 'undefined') {
swal({
html: message,
title: title,
type: type,
width: '24rem',
}).then((result) => {
return result.value;
});
}
else {
alert(message);
}
}
At the end of my PHP functions, i have an alert('success'), and then i redirect to another page. With the native JS alert, it waits me to click the OK button to continue. Now with this swal function, it shows the alert and redirects immediatly. Is there a way to avoid this behavior and act like the native alert, without changing the function signature?
The difference is that the alert() is modal. This means it blocks all other input and output until it's dismissed. The Sweetalert is not.
You can make it behave in a similar manner by using a callback function which you execute when the OK button is clicked in the Sweetalert. You can do that by passing the function to alert(), then calling it in the then() block, like this:
function alert(message, title = 'Test', type = 'info', callback) {
if (typeof(swal) != 'undefined') {
swal({
html: message,
title: title,
type: type,
width: '24rem',
}).then(() => {
callback && callback();
});
} else {
alert(message);
callback && callback();
}
}
// example usage:
alert('foo bar', 'title', 'info', function() {
window.location.assign('somewhere_else.php');
});

Angular - electron view does not update after model changes

I have a field that enables me to choose a folder from an electron dialog. On clicking the field, the dialog opens and I'm able to select the folder.
However, upon hitting ok, even though my model contains the folder's path, it does not reflect in the input field, until I click OUTSIDE the field (when it loses focus). How exactly do I fix this behaviour?
Template contains:
<input type="text" class="form-control" (click)="onClickPath($event)" [(ngModel)]="currentConfiguration.workspacePath" id="workspace-path" name="workspace-name" aria-label="workspace" aria-describedby="workspace-lable">
CurrentConfiguration.ts
export class CurrentConfiguration {
workspacePath: string;
}
configuation.component.ts
currentConfiguration: CurrentConfiguration = {
workspacePath: ""
};
//onClickedPath event:
onClickPath(event) {
console.log("clicked: ", event.target.id);
// open the dialog to select the directory
const dir = this.electronService.remote.dialog.showOpenDialog({
properties: ["openDirectory"],
title: event.target.id.split('-').join(" ")
}, (folderPath) => {
console.log(folderPath);
if (folderPath[0] == undefined) {
this.electronService.remote.dialog.showMessageBox({
type: "error",
buttons: ["ok"],
title: "Error",
message: "Please select the folder"
});
}
else{
// set the correct directoryPath.
this.currentConfiguration[event.target.id.split('-')[0] + 'Path'] = folderPath[0];
}
});
}
Note - this is a almost a dupe of This question Since it helped me resolve the issue, I'll post the answer.
Electron dialogs seem to function outside the angular zone and hence any updates to the data does no trigger angular to refresh the view.
In order to make the refresh happen, I had to execute the logic inside a zone like below:
import { NgZone } from '#angular/core';
...
...
currentConfiguration: CurrentConfiguration = {
workspacePath: ""
};
//onClickedPath event:
onClickPath(event) {
console.log("clicked: ", event.target.id);
// open the dialog to select the directory
const dir = this.electronService.remote.dialog.showOpenDialog({
properties: ["openDirectory"],
title: event.target.id.split('-').join(" ")
}, (folderPath) => {
console.log(folderPath);
if (folderPath[0] == undefined) {
this.electronService.remote.dialog.showMessageBox({
type: "error",
buttons: ["ok"],
title: "Error",
message: "Please select the folder"
});
}
else{
// run all of this inside the zone
this.zone.run(() => {
// set the correct directoryPath.
this.currentConfiguration[event.target.id.split('-')[0] + 'Path'] = folderPath[0];
}); // end of zone
}
});
}

I am unable to execute validation in Backbone.js.

Whenever I set the age attribute to negative value it doesn't return false.
I have also tried executing this code in the console and still nothing happens
<script>
var Human = Backbone.Model.extend({
// If you return a string from the validate function,
// Backbone will throw an error
defaults: {
name: 'Guest user',
age: 23,
occupation: 'worker'
},
validate: function( attributes ){
if( attributes.age < 0){
return "Age must me positive";
}
if( !attributes.name ){
return 'Every person must have a name';
}
},
work: function(){
return this.get('name') + ' is working';
}
});
var human = new Human;
human.set("age", -10);
human.on('error', function(model, error){
console.log(error);
});
</script>
There are a few things wrong with your code:
The event for validation is invalid, error is for ajax requests.
Validation on set doesn't happen by default, you need to pass { validate: true } as an option.
You are listening to the event AFTER setting, so it won't get called for that set.
i.e:
human.on('invalid', function(model, error) {
console.log(error);
});
human.set("age", -10, { validate: true });

autogenerated getter is undefined - ExtJS 4

This may be a duplicate question but in either case I wanted to ask.
I am a beginner ExtJS 4 developer and I am learning ExtJS using Loiane Groner's book, Mastering ExtJS 4. So far so good, but when I got to use refs the app breaks telling me that the autogenerated method is unavailable:
Here is my Login controller code:
Ext.define('Packt.controller.Login', {
extend: 'Ext.app.Controller',
requires:[
'Packt.util.MD5'
],
views:[
'Login',
'authentication.CapsLockTooltip'
],
refs: {
ref: 'capslocktooltip',
selector: 'capslocktooltip',
autoCreate : true
},
init: function(){
this.control({
"login form button#submit":{
click: this.onButtonClickSubmit
},
"login form button#cancel": {
click: this.onButtonClickCancel
},
"login form textfield": {
specialkey:this.onTextfieldSpecialKey
},
"login form textfield[name=password]": {
keypress: this.onTextfieldKeyPress
}
});
},
onTextfieldKeyPress: function(field, e, options){
var charCode = e.getCharCode();
if((e.shiftKey && charCode >= 97 && charCode <= 122) ||
(!e.shifKey && charCode >= 65 && charCode <= 90)){
if(this.getCapsLockTooltip() === undefined) {
Ext.widget('capslocktooltip');
}
} else {
if(this.getCapsLockTooltip() !== undefined) {
this.getCapsLockTooltip().hide();
}
}
},
onTextfieldSpecialKey: function(field, e, options){
if(e.getKey() == e.ENTER){
var submitBtn = field.up('form').down('button#submit');
submitBtn.fireEvent('click', submitBtn, e, options);
}
},
onButtonClickSubmit: function(button, e, options){
console.log('login submit');
var formPanel = button.up('form'),
login = button.up('login'),
user = formPanel.down('textfield[name=user]').getValue(),
pass = formPanel.down('textfield[name=password]').getValue();
if (formPanel.getForm().isValid()){
Ext.get(login.getEl()).mask("Authenticating... Please wait...", 'loading');
pass = Packt.util.MD5.encode(pass);
Ext.Ajax.request({
url:'php/login.php',
params:{
user:user,
password:pass
},
success: function(conn, response, options, eOpts){
Ext.get(login.getEl()).unmask();
var result = Ext.JSON.decode(conn.responseText, true);
if(!result){
result = {};
result.success = false;
result.msg = conn.responseText;
}
if(result.success){
login.close();
Ext.create('Packt.view.MyViewport');
} else {
Ext.Msg.show({
title:'Fail!',
msg: result.msg,
icon:Ext.Msg.ERROR,
buttons: Ext.Msg.OK
});
}
},
failure: function(conn, response, options, eOpts){
Ext.get(login.getEl()).unmask();
Ext.Msg.show({
title: 'Error!',
msg: conn.responseText,
icon: Ext.Msg.ERROR,
button: Ext.Msg.OK
});
}
});
}
},
onButtonClickCancel: function(button, e, options){
console.log('login cancel');
button.up('form').getForm().reset();
}
});
In firebug is see this:
TypeError: this.getCapsLockTooltip is not a function
I also was checking the Ext object inside Firebug and the closest thing to my function was this:
Ext.app.Application.instance.getController('Login').getAuthenticationCapsLockTooltipView();
But i didn't find the required function. What do I do wrong?
I follow the book and the above code is what you get.
Here is the caps lock view:
Ext.define('Packt.view.authentication.CapsLockTooltip', {
extend: 'Ext.tip.QuickTip',
alias: 'widget.capslocktooltip',
target: 'password',
anchor: 'top',
anchorOffset: 60,
width: 300,
dismissDelay: 0,
autoHide: false,
title: '<div class="capslock">Caps Lock is On</div>',
html:'<div>Having caps log on may cause you the enter password incorrectly.</div>'
});
The ref is case sensitive so the function what is created is getCapslocktooltip
When using refs see also Blessing and Curse of refs article
I found in the ExtJS 4 docs that refs is and array so when using it don't forget to add square brackets lik this:
refs:[
{
ref: 'capsLockTooltip',
selector: 'capslocktooltip'
}
]
http://docs.sencha.com/extjs/4.2.0/#!/api/Ext.app.Controller-cfg-refs
So now when you search JS memory with
Ext.app.Application.getController('Login').getCapsLockTooltip();
getCapsLockTooltip() function will exist. Also selector would be the alias name of the components you are trying to access.
Also just to note, Mastering ExtJS 4 by Loiane Groner has code errors.

Categories