AngularJS $interval dont stop on .cancel(); - javascript

I have SPA multi view application in AngularJS, I have defined $interval which is started from another view Controller. When i click a btn with function called and line $interval.cancel(); in it, it does not stop.
Here are examples of my code:
MainController:
$scope.$on("startInterval", function () {
$interval(function warningsControl() {
console.log("Timer stamp!");
$.ajax({
// some web api call which works fine
})
}, 10000);
});
$scope.stop = function () {
$interval.cancel();
}
$scope.logoutButton = {
text: "Logout",
type: "normal",
visible: false,
onClick: function () {
// some working code
$scope.stop();
var logoutBtn = $("#logout-btn").dxButton("instance");
logoutBtn.option({
visible: false
});
}
}
And SecondController:
$scope.authenticateButton = {
type: "default",
text: "Log In",
onClick: function () {
$.ajax({
// some web api calling
success: (data) => {
// some working code
$rootScope.$broadcast("startInterval");
}
})
}
}
This code start interval and everithing is running OK, until the point i click Logout btn - it made everithing except stoping the interval.
Any ideas how to fix it? I would be grateful for advice.

The $interval function should return some sort of ID which you can pass into $interval.cancel(). For example:
var int_id = $interval( func, time )
//...later...
$interval.cancel(int_id)

Related

Polymer1: addEventListener for Notify Not Working as Expected

I am trying to call window.addEventListener on my custom behavior however im not having any luck getting it to work.
test-bahvior.html
<script>
"use strict";
window.MyTest = window.MyTest || {};
MyTest.Test = {
properties: {
globals: {
type: Boolean,
notify: true,
value: false
}
},
ready: function() {
setTimeout(() => {
this.globals = true;
console.log('changed val ' + this.globals);
}, 5000);
},
};
</script>
i am then trying to callwindow.addEventListener("globals-changed", this._test); in the ready: function() of another html file (myapp.html) however this._test doesnt seem to fire despite the setTimeout causing the value change.
I have been following the Polymer 1 docs:
https://polymer-library.polymer-project.org/1.0/docs/devguide/properties#notify
Help is much appreciated.
TIA

How to add a process bar when you waiting for a response from the server

could someone help me with one problem? I want to add a process bar when you waiting for a response from the server (Django 3.x).
Step to reproduce:
On the page 'A' we have the form.
Enter data to form.
Submit POST request by clicking to button on the page 'A'.
Waiting for getting the result on the page 'A'.
Get the result on the page 'A'.
So, I want to add process bar after 4th and before 5th points on the page 'A'. When you will get the result on the page 'A' it should disappear.
Python 3.7
Django 3.x
You can use nprogress, it's a library used for progress bars. Use this inside the interceptor where you can config it for displaying only when request is in progress until finished.
There are lots of ways to do this. I think using jquery would be easier. Basically you just need to prevent submitting the page and do an Ajax request to server. something like
<script type='text/javascript'>
$(document).ready(function () {
$("form").submit(function (e) {
// prevent page loading
e.preventDefault(e);
$('#loadinAnimation').show();
// preapre formdata
$.ajax({
type: "yourRequestType",
url: "yourUrlEndpoint",
data: formdata,
success: function (data) {
$('#loadinAnimation').hide();
// do rest of the work with data
}
});
});
});
</script>
and show appropriate loading animation in your html part
<div id='loadinAnimation' style='display:none'>
<div>loading gif</div>
</div>
You can also do it using UiKit Library in Javascript on your Django Template Page.
Below code is when a file is Uploaded
In your template file (template.html)
<body>
..
<form>
<progress id="js-progressbar" class="uk-progress" value="0" max="100" hidden></progress>
...
<div class="uk-alert-danger uk-margin-top uk-hidden" id="upload_error" uk-alert></div>
...
</form>
</head>
<script type="text/javascript">
$(document).ready(function(){
var bar = document.getElementById('js-progressbar');
UIkit.upload('.js-upload-list', {
url: '',
name : "customer-docs",
params :{
"csrfmiddlewaretoken":"{{csrf_token}}"
},
method : "POST",
concurrent:1,
allow:'*.(csv|xlsx)',
beforeSend: function (environment) {
console.log('beforeSend', arguments);
// The environment object can still be modified here.
// var {data, method, headers, xhr, responseType} = environment;
},
beforeAll: function (args,files) {
console.log('beforeAll', arguments);
},
load: function () {
console.log('load', arguments);
},
error: function (files) {
console.log("---------------")
},
complete: function () {
console.log('complete', arguments);
},
loadStart: function (e) {
console.log('loadStart', arguments);
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
},
progress: function (e) {
console.log('progress', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
loadEnd: function (e) {
console.log('loadEnd', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
completeAll: function (data) {
console.log('completeAll', arguments);
console.log('completeAll', data);
let redirect_loc = ""
setTimeout(function () {
bar.setAttribute('hidden', 'hidden');
}, 1000);
// This is the response from your POST method of views.py
data.responseText = JSON.parse(data.responseText)
if(data.responseText.status == 201){
// swal is another library to show sweet alert pop ups
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Done: true
},
}).then((value) => {
switch (value) {
case "Done":
window.location.href = ""
break;
}
});
}
else if(data.responseText.status == 500){
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Ok: true
},
}).then((value) => {
switch (value) {
case "Ok":
window.location.href = ""
break;
}
});
}
}
});
// This block of code is to restrict user to upload only specific FILE formats (below example is for CSV & XLSX files)
(function() {
var _old_alert = window.alert;
window.alert = function(e) {
console.log(e)
if(e.includes("csv|xlsx") || e.includes("Invalid file type")) {
$("#upload_error").html("Invalid file format. Valid formats are CSV, XLSX").removeClass('uk-hidden')
}else if(e.includes("Internal Server Error")) {
$("#upload_error").html("Internal Server Error Kindly upload Documents again").removeClass('uk-hidden')
}
else {
_old_alert.apply(window,arguments);
$("#upload_error").addClass('uk-hidden').html("")
}
};
})();
});
</script>
On your views.py you can do your computation and once done, you can return a response like below
resp_json = {
"status" : 201,
"status_icon" : "success",
"url" : "/",
"message": message
}
return HttpResponse(json.dumps(resp_json))
For more info on SWAL (Sweet Alerts), visit https://sweetalert.js.org/guides/

RequireJS modules are undefined in Backbone view

I have been pretty much beginner at this part of javascript and I would appreciate any ideas how could be solved this problem.
I use requirejs to define my own modules where I also use backbone.js.
Let say I have the main module where I initialize my Backbone view which is rendered without any problem. Also, the click event where is calling method createSchemeForm creates the form correctly. The problem raises up in a situation when I call cancel method by click and the modules which are defined for Backbone view (e.g. "unicorn/sla/dom/helper"...) are undefined but when I called method createSchemeForm at the beginning the modules were executed without any problem.
Thank you in advance for any suggestions.
Backbone view
define("unicorn/sla/view/scheme", [
"unicorn/sla/dom/helper",
"unicorn/soy/utils",
"unicorn/sla/utils"
], function (DOMHelper, soyUtils, jsUtils) {
return Backbone.View.extend({
el: 'body',
inputData: {},
btnSaveScheme: 'btn-save-sla-scheme',
btnCancel: 'btn-cancel-sla-scheme',
btnCreate: 'btn-create-sla-scheme',
btnContainer: '#sla-scheme-buttons-container',
schemeContent: '#sla-scheme-content-section',
btnSpinner: '.button-spinner',
events: {
'click #btn-create-sla-scheme' : "createSchemeForm",
'click #btn-cancel-sla-scheme' : "cancel"
},
initialize: function(){
console.log("The scheme view is initialized...");
this.render();
},
createSchemeForm: function () {
this.spin();
DOMHelper.clearSchemeContent();
DOMHelper.clearButtonsContainer();
//Get button
$btnSave = soyUtils.getButton({isPrimary: 'true', id: this.btnSaveScheme, label: 'Save'});
$btnCancel = soyUtils.getButton({isPrimary: 'false', id: this.btnCancel, label: 'Cancel'});
//Append new created buttons
DOMHelper.addContent(this.btnContainer, AJS.format("{0}{1}", $btnSave, $btnCancel));
//Call service to get entry data for scheme creation form
AJS.$.ajax({
url: AJS.format('{0}={1}',AJS.I18n.getText('rest-url-project-scheme-input-data'), jsUtils.getProjectKey()) ,
type: "post",
async: false,
context: this,
global: false,
}).done(function (data) {
this.inputData = data;
$slaSchemeForm = soyUtils.getSchemeCreateForm({slaScheme : data, helpText: AJS.I18n.getText("sla-time-target-tooltip-text")});
DOMHelper.addContent(this.schemeContent, $slaSchemeForm);
jsUtils.scroll(this.schemeContent, 'slow');
}).fail(function () {
jsUtils.callFlag('error', AJS.I18n.getText("message-title-error"), AJS.I18n.getText("sla-error-load-scheme-input-data"));
}).always(function () {
this.stopSpin();
});
},
spin: function () {
AJS.$('.button-spinner').spin();
},
stopSpin: function () {
AJS.$('.button-spinner').spinStop();
},
cancel: function () {
jsUtils.clearButtonsContainer();
jsUtils.clearSchemeContent();
$btnCreateScheme = soyUtils.getButton({isPrimary: 'false', id: this.btnCreate, label: 'Create SLA Scheme'});
DOMHelper.addContent(this.btnContainer, $btnCreateScheme);
DOMHelper.addContent(this.schemeContent, soyUtils.getSchemesTable(new Array())); // TODO - get current data from server instead of empty array
}
});
});
Main module where is Backbone view initialize
define("unicorn/sla/project/batch", [
"unicorn/sla/utils",
"unicorn/sla/data/operations",
"unicorn/sla/data/validator",
"unicorn/sla/dom/helper",
"unicorn/sla/model/confirm/message",
"unicorn/sla/view/scheme",
"exports"
], function (jsUtils, operations, validator, DOMHelper, ConfirmMessage, SchemeView, exports) {
//Load project batch
exports.onReady = function () {
$schemeView = new SchemeView();
$schemeView.render();
}
});
AJS.$(function () {
AJS.$(document).ready(function () {
require("unicorn/sla/project/batch").onReady();
});
});

Backbone.js - History is creating two entries

I'm not sure how to express this in code, as I can't seem to locate the problem, but my issue is that Backbone.history seems to be recording two items when a user clicks on a list item in my app.
This is not consistent.
My app has a 4 item navigation at the bottom that links to 4 main sections (the first one being home - routed to '/'). If I load up the app, go to one of the other navigation pages, then click the 'Home' button again and then click one of the navigation options I get a list of items to choose from. If I then choose one two entries are added - Firstly, for some reason, a reference to the home route with /# at the end and then the route for the item I clicked.
The end result is that 'back' then inexplicably takes me to the home page.
If it helps, my router looks like this...
var siansplanRouter = Backbone.Router.extend({
initialize: function () {
var that = this;
this.routesHit = 0;
//keep count of number of routes handled by your application
Backbone.history.on('route', function() { that.routesHit++; }, this);
window.SiansPlanApp.render();
window.SiansPlanApp.router = this;
},
routes: {
'': 'showHome',
'home': 'showHome',
'hub': 'showHome',
'samples': 'showJqmSamples',
'mealplanner': 'showCurrentMealPlanner',
'mealplanner/:planId': 'showMealPlanner',
'recipes': 'showRecipeSearch',
'recipes/:recipeId': 'showRecipe',
'settings': 'showSettings',
'versioninfo': 'showVersionInfo',
'*other': 'showHome'
},
routesHit: 0,
back: function() {
if(this.routesHit > 1) {
window.history.back();
} else {
//otherwise go to the home page. Use replaceState if available so
//the navigation doesn't create an extra history entry
this.navigate('/', { trigger: true, replace: true });
}
},
showHome: function () {
SiansPlanApp.renderHome();
},
showJqmSamples: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.Hub.Samples());
},
showMealPlanner: function (planId) {
SiansPlanApp.renderView(new SiansPlanApp.views.Planner.MealPlanner({ id: planId }));
},
showCurrentMealPlanner: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.Planner.MealPlanner({ current: true }));
},
showRecipeSearch: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.Recipes.Search());
},
showRecipe: function (recipeId) {
SiansPlanApp.renderView(new SiansPlanApp.views.Recipes.Recipe({ id: recipeId }));
},
showSettings: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.System.Settings());
},
showVersionInfo: function () {
SiansPlanApp.renderView(new SiansPlanApp.views.About.VersionInfo.ListView());
}
});
I've got some basic elements in a kick off file too here...
define(['router', 'regions/r-app', 'jquery', 'domReady'],
function (SiansPlanRouter, AppRegion) {
var run = function () {
// Global click event handler to pass through links to navigate
$(document).on("click", "a:not([data-bypass])", function (e) {
var href = { prop: $(this).prop("href"), attr: $(this).attr("href") };
var root = location.protocol + "//" + location.host + SiansPlanApp.root;
if (href.prop && href.prop.slice(0, root.length) === root) {
e.preventDefault();
Backbone.history.navigate(href.attr, true);
}
});
$.ajaxPrefilter(function (options, originalOptions, jqXhr) {
//options.url = '/api' + options.url;
});
// Create the global namespace region object.
window.SiansPlanApp = new AppRegion();
// Adds the authorization header to all of the API requests.
$(document).ajaxSend(function (e, xhr, options) {
xhr.setRequestHeader("Authorization", 'SiansPlan ' + SiansPlanApp.cookies.getSessionData());
});
// Load up session data if any is present yet - this can't happen until the XHR headers are set up.
SiansPlanApp.session.loadSession();
// Instantiate the router.
window.SiansPlanApp.router = new SiansPlanRouter();
// Boot up the app:
Backbone.history.start();
};
return {
run: run
};
});

Why won't my jQuery-ui modal dialog display two custom buttons?

I have a generic Javascript function for displaying a jQuery-ui modal dialog with two buttons -- essentially "Continue" and "Cancel", though the text varies. I'm calling it in three places in my application. What's happening is that only the second button, the "Cancel" button is being displayed. Here's the function: (String.Format is an external function I always use since Javascript doesn't have one built-in - I know it isn't the problem.)
function DisplayModalDialog(titleText, bodyText, continueText, cancelText) {
//add the dialog div to the page
$('body').append(String.Format("<div id='theDialog' title='{0}'><p>{1}</p></div>", titleText, bodyText));
//create the dialog
$('#theDialog').dialog({
width: 400,
height: "auto",
modal: true,
resizable: false,
draggable: false,
close: function (event, ui) {
$('body').find('#theDialog').remove();
$('body').find('#theDialog').destroy();
},
buttons: [
{
text: continueText,
click: function () {
$(this).dialog('close');
return true;
},
text: cancelText,
click: function () {
$(this).dialog('close');
return false;
}
}]
});
return false;
}
And here's a snippet showing how I'm calling it:
if(CheckFormDataChanged() {
var changeTitle = "Data has been changed";
var changeText = "You have updated information on this form. Are you sure you wish to continue without saving?";
var changeContinue = "Yes, continue without saving";
var changeCancel = "No, let me save";
if (DisplayModalDialog(changeTitle, changeText, changeContinue, changeCancel)) {
if (obj) obj.click();
return true;
}
}
What's wrong with my function (or the call)?
UPDATE: Here's what I'm working with now. I realized that on one of the modal dialogs I didn't need a cancel button, just an acknowledge button:
function DisplayModalDialog(titleText, bodyText, continueText, cancelText, suppressCancel) {
var def = new $.Deferred();
//add the dialog div to the page
$('body').append(String.Format("<div id='theDialog' title='{0}'><p>{1}</p></div>", titleText, bodyText));
//create the button array for the dialog
var buttonArray = [];
buttonArray.push({ text: continueText, click: function () { $(this).dialog('close'); def.resolve(); } });
if (!suppressCancel) {
buttonArray.push({ text: cancelText, click: function () { $(this).dialog('close'); def.reject(); } });
}
//create the dialog
$('#theDialog').dialog({
... dialog options ...
close: function (event, ui) { $('body').find('#theDialog').remove(); },
buttons: buttonArray
});
return def.promise();
}
And the usage:
DisplayModalDialog(changeTitle, changeText, changeContinue, changeCancel, false)
.done(function () { if (obj) obj.click(); return true; })
.fail(function () { return false; });
Just to give you some context, obj is an ASP.Net Button being passed to the client-side function; if the function returns true, the server-side OnClick event is triggered; if false, it isn't. In this case, the server-side OnClick advances to the next tab in a TabContainer (among other things). What's happening is that it's moving to the next tab anyway, even though I'm returning false in the fail() function.
Your curly braces are off:
[{
text: continueText,
click: function () {
$(this).dialog('close');
return true;
}
}, {
text: cancelText,
click: function () {
$(this).dialog('close');
return false;
}
}]
As you have it, you only have one object in your buttons array.
I can't tell yet why the button doesn't display EDIT, ah, yes I can, there's a missing curly brace.
What I can tell you that your return lines simply won't work.
The dialog box gets displayed, your function returns immediately, and processing continues, so the click callback return values are completely ignored.
What you can do instead is return a promise:
function DisplayModalDialog(titleText, bodyText, continueText, cancelText) {
var def = $.Deferred();
...
buttons: [
{
text: continueText,
click: function () {
$(this).dialog('close');
def.resolve();
}
},
{ // ah - here's your button bug - a missing brace
text: cancelText,
click: function () {
$(this).dialog('close');
def.reject();
}
}
...
return def.promise();
}
with usage:
DisplayModalDialog(changeTitle, changeText, changeContinue, changeCancel)
.done(function() {
// continue was clicked
}).fail(function() {
// cancel was clicked
});

Categories