execute javascript method after completing code behind method? - asp.net

I want execute below callback() method after completion of document.getElementById('btnDownload').click(); method . Now callback()executing immediatly. I want wait "Click()" process done then Execute callback(); method.
function LoadPopup() {
// find the popup behavior
this._popup = $find('mdlPopup');
// show the popup
this._popup.show();
// synchronously run the server side validation ...
document.getElementById('btnDownload').click();
callback();
}
function callback() {
this._popup = $find('mdlPopup');
// hide the popup
this._popup.hide();
alert("hi");
}

Unless I've wildly misunderstood the question, this code will make a request to the page that the link leads to, and when the server has returned the response, executes the function:
$(document).ready(function() {
$("#btnDownload").click(function() {
$.ajax({
url: $(this).attr("href"),
complete: function(xhr, status) {
callback();
}
});
return false;
});
});
I may have wildly misunderstood the question...

Your question is not clear. But I will give you a example.
For example, you wan to load a page by clicking on a image then after the page load is complete you want to do something you can something like this
$('#buttonid').click(function() {
//this is the callback function of click event
//if you want some other callback functions then you need something like this
$("#somediv").load("page.php", function() {
//callback function code of .load event
alert('page loaded');
});
});
What you are asking is to have a callback function inside the default callback function of click event and a bit impossible from my point of view.

Related

refetchevents not getting new event

I use a function to get my events:
events: function (start, end, timezone, callback) {
$.ajax({
url: '/Controller/GetDiaryEvents/',
data: {
when I add a new event, the calendar does not show the newly added event. Do I need to reset my eventsource somehow ?
success: function (response) {
debugger;
if (response == true) {
$('#calendar').fullCalendar('refetchEvents');
alert('New event saved!');
}
This link FullCalendar refetchEvents not reloading calendar says to do Calendar..init but I don't see that method.
There is no need to refetch all events.
When new event is created add it to calendar using addEventSource function.
$("#calendar").fullCalendar( 'addEventSource', source );
Source may be an Array/URL/Function just as in the events option. Events will be immediately fetched from this source and placed on the calendar.
Simply add a function getEvents() and call it where you want to refetch
function getEvents()
{
$('#calendar').fullCalendar( 'refetchEvents' );
}

How do I create a countdown timer that persists when I browse to other pages of my app?

I'm making a simple app where I start a countdown timer, and when the timer expires it shows a template. On that template, I answer a series of questions, then then submit the answers to the database.
At the moment, my countdown timer just written in JavaScript like this:
Template.start.events({
'click .startTimer': function() {
$("#timer").text();
(function() {
var wait = 2;
var countSpan = $('#timer span');
function countdown() {
wait -= 1;
if (wait > 0) {
countSpan.text(wait);
setTimeout(countdown, 1000);
$('.startTimer').prop("disabled", true);
Session.set('done', false);
} else {
Session.set('done', true);
$('.startTimer').prop("disabled", false);
countSpan.text("Complete checkup then keep working!");
}
}
setTimeout(countdown, 1000);
}());
}
});
The problem is that when I navigate away from the page that's printing out the countdown, it doesn't persist.
How do I make a countdown timer within my app that will keep going while I navigate to other pages within the app?
What about this pseudo idea:
Once you navigate away form the page (tab blur of some sorts), save
variable in the Session with current timestamp
Session.set("leavingAt", new Date())
Once you return to the page (equivalent tab focus), save new variable with current timestamp
Session.set("returningAt", new Date())
Add/substract difference between both (depending on how you implement) and update your countdown timer
You could start the timer on the server using a Meteor method.
// call method from template
Meteor.call('startTimer', function() {
// handle timer finished logic
});
//server
Meteor.methods({
startTimer: function() {
Meteor.setTimeout(function() {
//do something
return;
}, ms)
}
});
I think your callback will still be triggered even if you're on a different template, but I'm not 100% sure.
I ended up using meteorhacks:async to accomplish this. Here's the code:
function delayedMessge(callback) {
Meteor.setTimeout(function() {
callback(null, true)
}, 1000)
}
var wrappedDelayedMessage = Async.wrap(delayedMessge);
Meteor.methods({
'abc': function() {
var response = wrappedDelayedMessage();
return response;
}
});
Template.start.events({
'click .start': function() {
Meteor.call('abc', function(error, response){
var timeup = response
//I'm setting this session to true, then in a helper
//that isn't shown here, I'm getting the Session and
//which displays the template
Session.set('done', timeup)
});
}
})
azium's answer led me in the right direction but wasn't quite right. I did end up running a setTimeout within a method but there was a problem. The callback associated with the Meteor.call is executed right away, but the setTimeout within the mehod hasn't finished yet. With the meteorhacks:async package, the Meteor.call callback function waits until the setTimeout fires.

Meteor callback to sys.exec inside a Meteor.call callback

I have an event triggering a Metor.call():
Meteor.call("runCode", myCode, function(err, response) {
Session.set('code', response);
console.log(response);
});
But my runCode function inside the server's Metheor.methods has inside it a callback too and I can't find a way to make it return something to response in the above code.
runCode: function(myCode) {
var command = 'pwd';
child = exec(command, function(error, stdout, stderr) {
console.log(stdout.toString());
console.log(stderr.toString());
// I Want to return stdout.toString()
// returning here causes undefined because runCode doesn't actually return
});
// I can't really return here because I don't have yet the valuer of stdout.toString();
}
I'd like a way to have the exec callback return something as runCode without setInterval which would work, but as a hacky way in my opinion.
You should use Future from fibers.
See docs here : https://npmjs.org/package/fibers
Essentially, what you want to do is wait until some asynchronous code is run, then return the result of it in a procedural fashion, this is exactly what Future does.
You will find out more here : https://www.eventedmind.com/feed/Ww3rQrHJo8FLgK7FF
Finally, you might want to use the Async utilities provided by this package : https://github.com/arunoda/meteor-npm, it will make your like easier.
// load future from fibers
var Future=Npm.require("fibers/future");
// load exec
var exec=Npm.require("child_process").exec;
Meteor.methods({
runCode:function(myCode){
// this method call won't return immediately, it will wait for the
// asynchronous code to finish, so we call unblock to allow this client
// to queue other method calls (see Meteor docs)
this.unblock();
var future=new Future();
var command=myCode;
exec(command,function(error,stdout,stderr){
if(error){
console.log(error);
throw new Meteor.Error(500,command+" failed");
}
future.return(stdout.toString());
});
return future.wait();
}
});

AngularJS - refresh view after http request, $rootScope.apply returns $digest already in progress

I am simply trying to load data when my app starts. However, the view loads faster than the http request(of course). I want to refresh my view once my data has been properly loaded because that data defines my view.
I've tried $rootScope.apply from inside the factory where I do my http request, and I also tried directly doing the http request in my controller again with $scope.apply, and neither one worked as they both gave me "$digest already in progress"
Any idea how can I set up my code to make my views refresh on data load? I will be having several different http requests and I would like to know how to set them up properly! I would really appreciate any input!
Here is some of the code I am working with.
app.factory('HttpRequestFactory', function($http, $q) {
var HttpRequestFactory = {
async: function(url, params) {
var deferred = $q.defer();
$http({
url: url,
method: post,
params: params
})
.success(function(data, status, headers, config) {
deferred.resolve(data);
})
.error(function(data, status, headers, config) {
deferred.reject("An error occurred");
});
return deferred.promise;
}
};
return HttpRequestFactory;
});
Factory
function initializeAll(){
HttpRequestFactory.async('../api', {action: 'getall'}).then(function(data) {
//$rootScope.$apply(function () {
allData = data;
//});
angular.forEach(allData, function(value, index){
console.log('Voala!');
});
});
}
Controller calling the factory's function initializeAll()
app.controller("MainController", ["$scope", "$rootScope","MyFactory",
function($scope, $rootScope, MyFactory){
MyFactory.initializeAll();
}
]);
Oh my !
You got the f** matter with AngularJS !
In fact you have to do a "safeApply" like that for example :
$rootScope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if(phase == '$apply' || phase == '$digest') {
if(fn && (typeof(fn) === 'function')) {
fn();
}
} else {
this.$apply(fn);
}
};
In AngularJS you can only have one $apply or $digest loop at the same time.
For details on these loops look at the docs :
http://docs.angularjs.org/guide/concepts
It will explain what is the $apply loop and you'll understand a lot of things about the two-way-data-binding in AngularJS
Hope it helps.
Don't use $apply: use $watch.
Calling $apply is (almost) always the wrong thing to do. The only time you should ever be calling it is if you've triggered a change outside of an 'angular' method; here, since the trigger occurs in an angular $http request, you can't call $apply because it's already being done at that moment by the $http block. Instead, what you want to do is $watch.
Official Doc for $scope.$watch() here
This will let you watch an object and update whenever it changes. I assume that your view is based on allData and you want it to update immediately; if you're using an ng method, then the watch is automatically setup for you and no more work should be needed. If you're using allData yourself inside a controller, you can write the watch in that controller like this:
$scope.$watch(function thingYouWantToWatch(){
return <accessor call to allData here>;
},
function whatToDoOnChange(newValue, oldValue){
$scope.myCoolThing = newValue; //this is the newValue of allData, or whatever you're watching.
}
);

Accessing this.userId not working when calling from within Meteor.SetTimeout

I've been trying to access the this.userId variable from within a Meteor.methods call, but it doesn't seem to work when I try to call the method via Meteor.setTimeout or Meteor.setInterval.
This is what I've got:
if (Meteor.is_server) {
Meteor.methods({
getAccessToken : function() {
try {
console.log(this.userId);
return Meteor.users.findOne({_id: this.userId}).services.facebook.accessToken;
} catch(e) {
return null;
}
}
});
var fetch_feed = function() {
console.log(Meteor.call("getAccessToken"));
[...] // A bunch of other code
};
Meteor.startup(function() {
Meteor.setInterval(fetch_feed, 60000); // fetch a facebook group feed every minute
Meteor.setTimeout(fetch_feed, 3000); // initially fetch the feed after 3 seconds
});
}
Watching the terminal log, the this.userId always returns a null. But if I try calling the method from the client side, or through the console, it returns the correct ID.
How come this doesn't work from within a Meteor.setInterval? Is it a bug or am I doing something wrong?
Meteor userId's are associated with client connections. The server may interact with many clients and this.userId inside a method will tell you which client has asked for the method to be run.
If the server uses Meteor.call() to run a method then it will not have a userId since it is not running for any client.
The methods allow clients to call for functions to be run on the server. For things the server will trigger itself a javascript function will do.
There is a solution I used - sometimes you do not want to make the method a function but really want it to remain a method. In that case, a hack to make this work:
var uniqueVar_D8kMWHtMMZJRCraiJ = Meteor.userId();
Meteor.setTimeout(function() {
// hack to make Meteor.userId() work on next async
// call to current method
if(! Meteor._userId) Meteor._userId = Meteor.userId;
Meteor.userId = function() {
return Meteor._userId() || uniqueVar_D8kMWHtMMZJRCraiJ
};
Meteor.apply(methodName, args);
}
, 100);
Some brief explanation: we save Meteor.userId in Meteor._userId and overwrite Meteor.userId with a function that returns Meteor._userId() if it is true and otherwise the historic value of Meteor.userId() before any of this happened. That historic value is saved in an impossible to occur twice var name so that no context conflicts can happen.

Resources