Featured post
javascript - How do I set a callback function parameter like 'data' in the "jQuery.ajax({ success : function(data)"? -
i wondering how set first parameter of callback function want, same way jquery in success callback or complete callback
i want this:
$.ajax({ success: function(data) { alert(data) } });
from understand close can want
function test(text) { this.text = text this.success = function(this.text) { } } var = new test('king kong') a.success = function(k){ alert(k) }
and want alert "king kong"
here's example of accepting callback in constructor function , calling later in response trigger. in below, trigger calling trigger
function, can want:
function test(text, callback) { this.text = text; this.success = callback; } test.prototype.trigger = function() { // call success callback, passing in text this.success(this.text); }; var = new test('king kong', function(k) { alert(k); }); a.trigger();
(i've made test
initially-capped there. that's convention constructor functions, of course free ignore.)
the key, fundamental thing understand functions objects else. can pass references them around, etc. call function, access whatever variable have function reference stored in , add parentheses (optionally function's arguments in parentheses).
consequently, of following call foo
function , trigger alert:
function foo(msg) { alert(msg); } var f = foo; // no parens, getting function reference, not calling f("hi there"); // we're calling var = {}; a.nifty = f; a.nifty("hi again"); function bar(func) { func("hello third time"); } bar(foo); // passing reference `foo` `bar` function, call
advanced: now, 1 thing jquery calls callback this
value set specific (usually dom element related call). happen time call function via object property:
var = {name: "fred"}; a.func = function() { alert(this.name); }; a.func(); // alerts "fred"
...but that's not way can it; there's call
, apply
functions on function object itself:
var = {name: "fred"}; function func() { alert(this.name); } func.call(a); // alerts "fred"
there, function isn't assigned of a
's properties, we've called function using call
, accepts value this
first argument. call passes on further arguments function you're calling:
function func(msg1, msg2) { alert(this.name + " says " + msg1 + " , " + msg2); } var = {name: "fred"}; func.call(a, "one", "two"); // alerts "fred says 1 , two"
apply
same thing, accepts arguments pass on underlying function array instead of discrete arguments:
function func(msg1, msg2) { alert(this.name + " says " + msg1 + " , " + msg2); } var = {name: "fred"}; func.apply(a, ["one", "two"]); // alerts "fred says 1 , two" // ^------------^----- note these args array
more reading: mythical methods
- Get link
- X
- Other Apps
Comments
Post a Comment