Getting Error on Two Events happening on same time - javascript

I'm having the activiti Bpmn file, in that there is having transition of task. While transition I need to create the due date for that new task. my problem is due date and new task happening on same time. because of that I'm getting error.
onClose: function (date) {
if (valid) {
date = Date.parse(date);
if (oldDate !== date) {
var tasks = getSet(context, 'task') || getSet(context, 'tasks'),
trans = Ember.get(context, 'transition') || Ember.get(context, 'propertyMap.transition'),
requestData = [];
if (!tasks.length) {
resolve();
return;
}
if (!trans) {
trans = 'Done';
}
tasks.forEach(function (task) {
requestData.push({ name: 'id', value: (Ember.get(task, 'id') || Ember.get(task, 'currentTask.id') )});
requestData.push({ name: 'transition', value: trans || '' });
});
if (context.get('serviceParams')) {
Object.asAjaxData(context.get('serviceParams')).forEach(function (param) {
requestData.push(param);
});
}
return (Core.services({
type: 'post',
service: 'workflow/task/transition',
data: requestData,
json: true
})
.done(function (res) {
Core.Action('Core:updateTask', context, { dtDue: date });
Core.model.ingestResources(res);
var inspected = Core.controller.detailsObject,
wf = res.workflows || {};
if (inspected) {
Object.keys(wf).forEach(function (w) {
var hist = wf[w].historicalTaskIds;
if (hist.contains(inspected.currentTaskId)) {
inspected.set('currentTaskId', wf[w].openTaskIds[0]);
}
});
}
resolve();
})
.fail(function (xhr, status, error) {
Core.Error.show(error);
})
.always(function () {
tasks.forEach(function (task) {
if (Ember.get(task, 'isClip')) {
Core.model.clip.clear();
}
});
var wfController = Core.Tab.Workflow.getController();
var sel = wfController.get('selection');
wfController.reloadResultSet();
var rs = wfController.get('resultSet');
rs && rs.done(function () {
var s = Ember.Set.create();
rs.get('content').forEach(function (item) {
if (!item) { return; }
s.addObject(item);
});
sel.forEach(function (item) {
if (!s.contains(item)) {
sel.remove(item);
}
});
});
sel.clear();
resolve(tasks);
})
);
}
}
}
In that Core.Action('Core:updateTask', context, { dtDue: date }); is using for updating the duedate. If I use on the top If statement Due Date is updated, but Transistion is not happening. If I'm using on the done function, the transistion is happened and moved to the new Task Id. Because of that it searching Task Id and showing error.
Please provide me suggestion on this. I need to create both the Transistion and meanwhile update the date.

Related

Keep LocalStorage after refreshing page

Currently, I enter data, it stores in the local storage and displays it accordingly. Here is the code for that flow:
Creating/Setting Data (in the create.js file)
let orders = [];
document.onreadystatechange = function () {
if (document.readyState === 'interactive') renderApp();
function renderApp() {
var onInit = app.initialized();
onInit.then(getClient).catch(handleErr);
function getClient(_client) {
window.client = _client;
//client.events.on('app.activated', onAppActivate1);
onAppActivate1();
}
}
};
function onAppActivate1() {
//intialize an array that will have all the keys user puts in
console.log('got here');
$("#btnCreateOrder").click(function () {
//orders = localStorage.getItem('orderlist');
let order = {
id: Date.now(),
order: document.getElementById('order').value,
name: document.getElementById('inputName').value,
date: document.getElementById('inputDate').value,
status: document.getElementById('inputStatus').value
}
orders.push(order);
if (!localStorage.getItem('orderlist') || JSON.parse(localStorage.getItem('orderlist')).length === 0) {
$window.localStorage.setItem('orderlist', JSON.stringify($scope.initData));
}
//localStorage.setItem('orderlist', JSON.stringify(orders));
client.instance.send({
message: {
orders: orders
}
});
client.instance.close();
});
}
function handleErr(err) {
console.log('Error Occuered', err);
}
Receiving/Displaying data (app.js)
function onAppActivate() {
//var displayID = new Array();
console.log("Hi!! We are in the app!");
client.instance.resize({ height: "350px" });
client.instance.receive(function (event) {
var data = event.helper.getData();
console.log("data is", data);
for (let i = 0; i < data.message.orders.length; ++i) {
console.log(data.message.orders.length);
const orderList = data.message.orders[i];
console.log("orderlist is ", orderList);
var order = document.createElement("div");
order.innerHTML = `<br/> Order#: ${orderList.order}<br/> Name: ${orderList.name}<br/>
Date: ${orderList.date} <br/> Status: ${orderList.status}`;
order.style.borderBottom = "1px solid black"
document.getElementById('orderhistory').appendChild(order);
}
})
when i refresh the app, my data stays but when i reload the browser, the data gets reset but I want the data to stay even if i reload the browser and keep appending to it

How to get value of json web API using VueJS

I am new to Vue.JS. Actually I am trying to get Name of bank by typing routing number.
API: https://www.routingnumbers.info/api/name.json?rn=011103093
export default {
data: function () {
return {
picker: new Date().toISOString().substr(0, 7),
resultsArray: {
'name' : '',
'message' : '',
'code' : '',
'rn' : ''
},
}
}
}
methods: {
/* searchBasedOnMonthAndType() {
let app = this;
app.modeldailog = false
app.rows = [];
app.renderInvoicesBasedOnMonth(app.picker);
},*/
getBankName() {
let app = this;
app.rows = [];
var rn = '011103093';
$.ajax({
url: 'https://www.routingnumbers.info/api/name.json?rn=' + rn,
success(res) {
if (res.results != null) {
app.resultsArray = res.results;
} else {
// console.log(app.resultsArray);
// console.log("test after");
alert("data not fetched");
}
}
});
},
}
<label>Routing Number</label>
<input type="text" name="routingNo" v-validate="'required|numeric'" v-model="paymentinfo.routing_no" class="form-control input-sm" v-on:keyup="getBankName();">
<label>Bank Name</label>
<input type="text" name="chck_bank_name" v-validate="'required'" class="form-control input-sm" v-bind:value="resultsArray.name">
I am getting Ajax response null. Everytime else part is being executed.
Maybe you typo in options for $.ajax method. Try this:
getBankName() {
let app = this;
app.rows = [];
var rn = '011103093';
$.ajax({
url: 'https://www.routingnumbers.info/api/name.json?rn=' + rn,
success: (res) => {
if (res != null) {
app.resultsArray = res;
} else {
// console.log(app.resultsArray);
// console.log("test after");
alert("data not fetched");
}
}
});
},
FYI: result of that api call is not array. it's like so:
{"name": "TD BANK NA", "message": "OK", "code": 200, "rn": "011103093"}
Looks like you should use something like this:
$.ajax(...).done(data => {
console.log(data)
}).fail(() => {
console.log('fail')
})
P.S. It's better to use const vm = this; instead of let app = this;. It's de-facto standart in Vue.js

How to return templates from cache or ajax load?

In my code I try to load templates from cache. If template does not present in cache - load template from server by ajax. When loading is finished, I want to put template to cache and return it. Here is it:
var manager = function () {
return {
cache: [],
getTemplate: function (templateId) {
this.templateId = templateId;
if (this.cache[this.templateId]) {
return this.cache[this.templateId];
}
return this.loadTemplate();
},
loadTemplate: function() {
var
self = this;
$.get('/assets/templates/' + this.templateId + '.html', function (templateHtml) {
self.cache[self.templateId] = templateHtml;
return self.getTemplate(self.templateId);
});
}
}
}
var
manager = manager();
$('body').append( manager.getTemplate('template') );
I know that my code does not working because ajax request finished after function loadTemplate end. I think code can be fixed with deferred object but don't know how. Can anyone help me to find a solution?
There are two way of achieving your goal:
Promises (there are a lot of libs/shims). I'll rewrite it to ES6 just for the learning:
let manager = function () {
return {
cache: [],
getTemplate(id) {
let cache = this.cache;
return new Promise((resolve, reject) => {
if (cache[id]) {
resolve(cache[id]);
} else {
this.loadTemplate(id)
.then(template => {
cache[id] = template;
resolve(template);
})
.fail(reject);
}
});
},
loadTemplate(id) {
return $.get('/assets/templates/' + id + '.html');
}
}
};
let manager = manager();
manager.getTemplate('template').then((template) => {
$('body').append(template);
});
Callbacks:
let manager = function () {
return {
cache: [],
getTemplate(id, cb) {
let cache = this.cache;
if (cache[id]) {
cb(cache[id]);
} else {
this.loadTemplate(id)
.then(template => {
cache[id] = template;
cb(template);
});
}
},
loadTemplate(id) {
return $.get('/assets/templates/' + id + '.html');
}
}
};
let manager = manager();
manager.getTemplate('template', (template) => {
$('body').append(template);
});
Here's how you would do it, supporting all major browsers, and caching the requests too. This way you will only perform 1 request per template. (The other answers only cache the response).
var Manager = function() {
return {
cache: [],
getTemplate(id) {
var that = this;
if (that.cache[id] && that.cache[id].then){
console.log("Promise cache");
return that.cache[id]; //return promise from cache
}
return $.Deferred(function() {
var def = this;
if (that.cache[id]) {
console.log("Retrieved from cache!");
return def.resolve(that.cache[id]); //return cached template
}
that.cache[id] = def; //Cache promise
console.log("Retrieving template...");
that.loadTemplate(id).then(function(template) {
that.cache[id] = template;
def.resolve(template)
}).fail(function() {
def.reject();
});
return that.cache[id]; //return promise
}).promise();
},
loadTemplate(id) {
return $.get('https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js');
}
}
};
var manager = Manager();
manager.getTemplate('template').then(function(template){
console.log("loaded 1");
});
//This will use the promise from the first call (1 Request only)
manager.getTemplate('template').then(function(template){
console.log("loaded 2");
manager.getTemplate('template').then(function(template){
console.log("loaded 3"); //This will be retrieved fully from cache
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
As you are fetching the template via AJAX, you will be able to append the result only in AJAX success. So you need to pass the append logic as callback.Check the below code.
var manager = function () {
return {
cache: [],
getTemplate: function (templateId,callback) {
this.templateId = templateId;
if (this.cache[this.templateId]) {
callback(this.cache[this.templateId]);
}
this.loadTemplate(callback);
},
loadTemplate: function(callback) {
var
self = this;
$.get('/assets/templates/' + this.templateId + '.html', function (templateHtml) {
self.cache[self.templateId] = templateHtml;
callback(templateHtml)
});
}
}
}
var
manager = manager();
manager.getTemplate('template',function(result) {
$('body').append( result );
});
You may not need 2 functions to do this. So you can make it as one

Undefined variable in modularized script

I've been working at making this script more modularized toady, and I am running into an error. Am I ordering my logic incorrectly?
Error Msg
Uncaught ReferenceError: accountId is not defined
Related Script Line
_.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
accounts[accountId].push([result.timestamp.valueOf(), 0]);
});
Script
var debug = 0;
function paramsStr(p) {
var first = true;
var s = '';
_.each(p,function (value,key) {
if (!value) {
return;
}
if (first) {
s += '?';
first = false;
} else {
s += '&';
}
s += key+'='+value;
});
return s;
};
function parseReport(data)
{
var split = data.split('\n');
var results = [];
_.each(split,function (row) {
if (!row || row == "") {
return;
}
var myRow = JSON.parse(row);
myRow.timestamp = moment.utc(myRow.timestamp);
results.push(myRow);
});
return results;
}
function loadReport(report,granularity,startTime,endTime) {
if (debug && _.has(mock.reports,report) && _.has(mock.reports[report],granularity)) {
return jQuery.Deferred().resolve(parseReport(mock.reports[report][granularity])).promise();
}
var params = {
granularity : granularity
};
if (startTime) {
params['start-time'] = startTime.toISOString();
}
if (endTime) {
params['end-time'] = endTime.toISOString();
}
var url = '//analytics.locuslabs.com/api/reports/'+report+paramsStr(params);
return $.ajax({
url : url,
dataType : 'text'
}).then(function (data) {
return parseReport(data);
});
};
$(document).ready(function () {
var placeholder = $(".graph");
var oneMonth = moment().utc().subtract(1, 'months');
var twoWeeks = moment().utc().subtract(2, 'weeks');
//Function call to get the current time
function dateNow(target,timeFormat){
$(placeholder).siblings(target).text(moment(Date.now()).format(timeFormat));
}
function pollData(apiRoot,increment,startDate,label){
loadReport(apiRoot,increment, startDate).then(function (results) {
var totals = [];
var accounts = {};
_.each(results, function (result) {
totals.push([
result.timestamp.valueOf(),
result.data.total
]);
_.each(result.data.accounts, function (account, accountId) {
if (!_.has(accounts, accountId)) {
accounts[accountId] = {
label: account.account.name,
data: []
};
}
accounts[accountId].data.push([
result.timestamp.valueOf(),
account.total
]);
});
_.each(_.omit(accounts, _.keys(result.data.accounts)), function (account) {
accounts[accountId].push([result.timestamp.valueOf(), 0]);
});
});
var data = [{
data: totals,
label: label
}];
_.each(accounts, function (account) {
data.push(account);
});
$(this > ".graph").plot(data, {
grid: {
hoverable: true
},
tooltip: {
show: true
},
xaxis: {
mode: "time"
},
yaxis: {
axisLabel: label
},
legend: {
container: $(this > ".legend")
},
selection: {
mode: "x"
}
});
});
// Reload function within pollData function
document.getElementById(apiRoot + "-reload").addEventListener("click", function() {
pollData(apiRoot,increment,startDate,label);
dateNow(".status","M/D/YYYY H:mm Z");
}, false);
}
//Load Reports
pollData('total-installs', 'day', oneMonth, "Total Installs");
pollData('installs', 'hour', twoWeeks, "Installs (by hour)");
pollData('sessions', 'day', twoWeeks, "Sessions");
pollData('sessions-length', 'day', twoWeeks, "Session Length");
// Selection Feature
// TODO: Add Zoom to selection
// TODO: Overview of Available Data when zoomed.
placeholder.bind("plotselected", function (event, ranges) {
var begin = ranges.xaxis.from.valueOf();
var end = ranges.xaxis.to.valueOf();
$(this).siblings(".selection").text(moment(begin).format("M/D/YYYY H:mm Z") + " to " + moment(end).format("M/D/YYYY H:mm Z"));
/*
var zoom = $("#zoom").prop("checked");
if (zoom) {
$.each(plot.getXAxes(), function(_, axis) {
var opts = axis.options;
opts.min = ranges.xaxis.from;
opts.max = ranges.xaxis.to;
});
plot.setupGrid();
plot.draw();
plot.clearSelection();
}
*/
});
// Update on Initial Poll
// TODO: Ask for location and provide local time.
dateNow(".status","M/D/YYYY H:mm Z");
});
You have no accountId parameter in your function
function (account) {
accounts[accountId].push([result.timestamp.valueOf(), 0]);

While trying to download a page, why doesn't this code alert test?

I have to download myURLString (http://www.google.com/search?q=http://www.google.com/&btnG=Search+Directory&hl=en&cat=gwd%2FTop).
function getcontents(myURLString) {
var gChannel;
var ioService = Components.classes["#mozilla.org/network/io-service;1"].getService(Components.interfaces.nsIIOService);
var uri = ioService.newURI(myURLString, null, null);
gChannel = ioService.newChannelFromURI(uri);
var listener = new StreamListener(callbackFunc);
gChannel.notificationCallbacks = listener;
gChannel.asyncOpen(listener, null);
function StreamListener(aCallbackFunc) {
this.mCallbackFunc = aCallbackFunc;
}
StreamListener.prototype = {
mData: "",
onStartRequest: function (aRequest, aContext) {
this.mData = "";
},
onDataAvailable: function (aRequest, aContext, aStream, aSourceOffset, aLength) {
var scriptableInputStream = Components.classes["#mozilla.org/scriptableinputstream;1"].createInstance(Components.interfaces.nsIScriptableInputStream);
scriptableInputStream.init(aStream);
this.mData += scriptableInputStream.read(aLength);
},
onStopRequest: function (aRequest, aContext, aStatus) {
if (Components.isSuccessCode(aStatus)) {
this.mCallbackFunc(this.mData);
alert('test');
} else {
this.mCallbackFunc(null);
}
gChannel = null;
},
onChannelRedirect: function (aOldChannel, aNewChannel, aFlags) {
gChannel = aNewChannel;
},
getInterface: function (aIID) {
try {
return this.QueryInterface(aIID);
} catch (e) {
throw Components.results.NS_NOINTERFACE;
}
},
onProgress : function (aRequest, aContext, aProgress, aProgressMax) { },
onStatus : function (aRequest, aContext, aStatus, aStatusArg) { },
onRedirect : function (aOldChannel, aNewChannel) { },
QueryInterface : function(aIID) {
if (aIID.equals(Components.interfaces.nsISupports) ||
aIID.equals(Components.interfaces.nsIInterfaceRequestor) ||
aIID.equals(Components.interfaces.nsIChannelEventSink) ||
aIID.equals(Components.interfaces.nsIProgressEventSink) ||
aIID.equals(Components.interfaces.nsIHttpEventSink) ||
aIID.equals(Components.interfaces.nsIStreamListener))
return this;
throw Components.results.NS_NOINTERFACE;
}
};
}
I'm thinking this.mData should have the page's contents, but I can't alert it, so I'm trying first to alert test. What is wrong?
UPDATE: I'm trying now...
function callbackFunc(pagecontents) {
alert(pagecontents);
}
...but it isn't called. Why?
I suspect you are getting an error since StreamListener is defined after you call new StreamListener(...). Have you set the proper developer preferences?

Categories

Resources