How do i execute a callback in a jQuery Plugin code - javascript

This may sound really like a newbie .. But i used the jQuery Boilerplate on this page - http://stefangabos.ro/jquery/jquery-plugin-boilerplate-revisited/ and created a plugin. Everything works fine, except now i want to add a callback. I want to execute this -
$.Alerter({'message':'this is a test','onSuccess':function(data) { alert(data); } });
The onSuccess is a callback function which is added to the defaults.
My question is – how do i send the output to the onSuccess. I want it to return back a TRUE or FALSE value after certain steps have been executed in the init()

Something like this:
plugin.result = null;
plugin.init = function() {
// do stuff
...
// save _result in public variable result
plugin.result = _result;
}
If you are writing this plugin for dom operations, you could also use it like plugin.data('result',_result);
Since I don't know anything else I can't give further insight.
Hope this will help you.

Related

How to call a function after "Complete page load" and "after all external script execution"?

How to call a function after "Complete page load" and "after all external script execution" ?
I tried all 4 below option, but no luck!!!
$(document).ready..
$(window).load...
window.onload = ...
$(document).ready(function()...
Doing setTimeout works for me, But not sure if this 100% efficient!!!!
setTimeout(function(){
//your code here
}, 3000);
Please advice and help!!!
I have been terribly interested with your question and going deep to the jQuery source I came up with a mad hack :)
But the key point is that you should put this piece of code at the very beginning, right after you plug jQuery:
$.statesNum = 0;
$.fn.ready = function ( fn ) {
$.statesNum++;
jQuery.ready.promise().done( fn ).then(function () {
$.statesNum--;
if ($.statesNum == 0) {
$(document).trigger("afterReady");
}
});
return this;
};
Now whenever you want to execute something after all .ready functions are done you can do like this:
$(document).on("afterReady", function () {
alert("Hey, the ready functions are executed");
});
Scripts are loaded and executed in the order they appear in your HTML. If you have simple scripts, just put things you want to run later at the bottom.
However if you have complex scripts that run asynchronously (meaning they run in parallel), then it is impossible to know if they have finished executing without actually looking at what they do. E.g. do they (or can they) trigger an event that you can listen to? Or maybe you can use "promise" patterns.

Can I make Javascript always call a method after JQuery Load?

We have started using jquery load in our site to load contents into a div rather than re-loading whole page. However in the complete function we have a method that re-applies various bindings. Is it possible to provide load method with a default complete function? So developers don't have to specify it in the jquery load complete function.
As we currently are providing a lot of duplicate complete functions
E.g.
$('#Target').load(callBackRedirect, function () {
ApplyBindings('#Target');
});
These bindings can't be applied using on and need to be re-applied on page loads. We also do some other work that we want to do on every page load.
The answer is no.
You need the callback because that's what the method calls when the request is done.
This works with on method to, you might be doing something wrong out there in the code.
You could create a helper function for this.
function loadSomething(targetElement, uri,callback) {
targetElement.load(uri, callback);
}
loadSomething(
$('myElement'),
'mylink.com/content',
function() {
applyBindings($(this));
}
)
Yes. Check out the list of Global AJAX Event Handlers.
e.g.
$(document).ajaxComplete(function() {
alert('Triggered ajaxComplete handler.');
});
That said, you shouldn't need to reapply your bindings after an AJAX call. If you need to do this, you're probably doing something wrong. Check out jQuery.on, which explains how to bind to content which is added dynamically.
Try $.ajaxSetup:
$.ajaxSetup({
complete: function() {
ApplyBindings('#target');
}
});
EDIT
You could also make a named function like:
var ajaxApplyBindings = function() {
ApplyBindings('#Target');
// anything else...
};
And then pass it to load:
$('#Target').load(callBackRedirect, ajaxApplyBindings);

Jquery DOM events called after events following it are executed

I am facing a very weird issue in chrome.
My code is
$('#import').text("Importing...");
$('#import img').removeClass("hidden");
Server.postService("tests", row_datas, function(data) {
// some stuff here
});
The text and the hidden class are being removed after the post action has been executed.
The code is working fine in firefox.
The only thing needed was
Server.async = true
before the server call.
Asynchronous functions fire in order of appearance but return in order of when they finish. It would be odd for those simple text and removeClass methods to return more slowly than whatever you're doing with your Server object, but I suppose it's possible. If you need the first two lines to happen before the postService, you might try jQuery's deferred.promise. Here's a fiddle demonstrating the potential, and some code to inspect:
function firstThing (){
var dfd = new jQuery.Deferred();
$('#import').text("Importing...");
$('#import img').removeClass("hidden");
dfd.resolve();
}
$.when( firstThing() ).then(
function() {
Server.postService("tests", row_datas, function(data) {
// some stuff here
});
}
)
As a side note, the logic of your code is problematic in that by setting the text of #import, whatever img had the hidden class won't be there anymore, but that might be beside the point.
Update
Noticing your response to my comment asking about your use of ajax, I would suggest you read about the async option and see how what you're doing might or might not be blocking events.
I would also recommend reading about jQuery ajax callbacks, particularly error, success, and complete (now, with jQuery 1.8+, fail, done, and always).

How to 'queue' piece of code in javascript

I've made a class that, when initialized, starts to download a JSON file.
However, the downloading runs asynchronously.
So after I declare it I start working with it, but it fails because it hasn't loaded the file yet.
I could turn async off, but is there another way without freezing the browser?
I'm currently working around it with a setTimeout option, but that seems like an ugly hack.
var d;
$(document).ready(function() {
d = new Duk('element');
d.getBlueprint('hud.json');
setTimeout(start, '2000');
});
function start(){
test = new d.Dialog(d.blueprint.screens.test);
test.draw();
}
You have to attach event handler to the object load completion event. The library you are working with must supply this event. I don't know what a Duk is, or what getBlueprint() does, but you should check the documentation for whatever that class and method is, and see if there is an oncomplete callback. If there is, you'd do something like this:
$(document).ready(function() {
d = new Duk('element');
d.getBlueprint('hud.json', {
onComplete: function() {
test = new d.Dialog(d.blueprint.screens.test);
test.draw();
}
});
});
Obviously, I just made that up. I don't know if your library has an onComplete method defined like this, but I hope you see what I mean. Without knowing more about the library you are using, I can't give a better example.
Timeouts are not the way to solve this problem.
You want to set up a callback function alongside the request so that the object handling the request knows what to do when the response comes in.
It is unclear from your code what framework you're using (I can't make any sense of getBlueprint, which seems to be the call that initializes the remote request), so if you could provide more information on this, we can provide more customized help.
You want your getBlueprint() method to be able to accept a callback which is run when the file is finished downloading.
function getBlueprint(file, callback)
{
// do whatever to get the file
// ...
// trigger the callback
callback();
}
$(document).ready(function() {
var d;
function start(){
test = new d.Dialog(d.blueprint.screens.test);
test.draw();
}
d = new Duk('element');
d.getBlueprint('hud.json', start);
setTimeout(start, '2000');
});
I agree that a callback function is the proper way. If this is code you cannot modify, you can do something like this, but seriously, use a callback!
function wait_for_load(expr, func)
{
var interval = window.setInterval(function()
{
if(eval(expr))
{
window.clearInterval(interval);
func();
}
}, 20);
}
var d;
$(document).ready(function() {
d = new Duk('element');
d.getBlueprint('hud.json');
wait_for_load('d.blueprint', start);
});

Add console.profile statements to JavaScript/jQuery code on the fly

We have a thick client app using jQuery heavily and want to profile the performance of the code using firebug's console.profile API. The problem is, I don't want to change the code to write the profile statements. Take this example:
var search=function(){
this.init=function(){
console.log('init');
}
this.ajax=function(){
console.log('ajax');
//make ajax call using $.ajax and do some DOM manipulations here..
}
this.cache=function(){
console.log('cache');
}
}
var instance=new search();
instance.ajax();
I want to profile my instance.ajax method, but I dont want to add profile statements in the code, as that makes it difficult to maintain the code.
I'm trying to override the methods using closures, like this: http://www.novogeek.com/post/2010/02/27/Overriding-jQueryJavaScript-functions-using-closures.aspx but am not very sure how I can achieve. Any pointers on this? I think this would help many big projects to profile the code easily without a big change in code.
Here is the idea. Just run the below code in firebug console, to know what I'm trying to achieve.
var search=function(){
this.init=function(){
console.log('init');
}
this.ajax=function(){
console.log('ajax');
//make ajax call using $.ajax and do some DOM manipulations here..
}
this.cache=function(){
console.log('cache');
}
}
var instance=new search();
$.each(instance, function(functionName, functionBody){
(function(){
var dup=functionBody
functionBody=function(){
console.log('modifying the old function: ',functionName);
console.profile(functionName);
dup.apply(this,arguments);
console.profileEnd(functionName);
}
})();
console.log(functionName, '::', functionBody());
});
Now what I need is, if i say instance.ajax(), I want the new ajax() method to be called, along with the console.profile statements. Hope I'm clear with the requirement. Please improvise the above code.
Regards,
Krishna,
http://www.novogeek.com
If you only want to modify the single instance of "search" then this should work:
$.each(instance, function(name, method){
if (typeof method !== 'function') return;
instance[name] = function() {
console.profile(name);
var ret = method.apply(this, arguments);
console.profileEnd(name);
return ret;
};
});
I know this is from a long time ago but I wanted to add this in case other people find this answer. You can make anonymous/private functions work by adding a name to each one. The other comments mention doing it manually bit I wanted to explain how to:
$('.stuff').each(function() { ... });
to
$('.stuff').each(function workOnStuff() { ... });

Categories

Resources