Friday, October 28, 2011

Example: Small Javascript library

In jQuery you can call a function like $.ajax() and insert an object inside of it and each property does an action. Below I have simplified an example to demonstrate how this works.


//create the library
var lib = {
sum: function(num){ //create a method
var num1 = num.a;
var num2 = num.b;
this.result = num1 + num2;
},
table: 'table' //this is a random property, its not necessary
}

//call a method and create an object inside of it to send data to the library
lib.sum({
a : 1, //these are the properties that will be processed
b : 4
});
alert(lib.result); //output 5



//above is similar to the jQuery AJAX below
$("#input").keyup(function(){
var data = $('#input').val();
$.ajax({
url:"models/post.php", //these are the properties that will be processed
type: "post",
data: ({name:data, age:'15'}),
success:function(result){$(".result").html(result);}
});
});



jQuery Deconstructed is a rather nice way to look through the source. You will learn alot by studying it.

No comments:

Post a Comment