In javascript we can express objects using the prototype notation:
var Cat = function () {
this.furry = true;
}
Cat.prototype.greet = function () {
return "meeow";
}
using class mimicking from prototype-js it would be :
var Cat = new Class({
initialize: function (){
this.furry = true;
},
ask: function (item) {
return "icanhas "+item+" ?";
});
This example should be pretty clear. But when we get into real-life application scenarios we need to interact with users and databases.
Let’s say we had a panel and a button for interacting with lolcats:
var CatInformationPanel = Class.create({
initialize: function (container) {
$(container.id+'_furry').checked = true;
$('petButton').observe('click', this.ask.bindAsEventListener(this));
},
ask: function (item) {
$(container.id+'_text').value ="icanhas "+item+" ?";
}
});
Note that we need to bind “this” to the the function scope for “ask”. this is one of the intricacies of object oriented javascript. Here are some badass ninja examples to explain why.
Now, after interacting with user , you probably want to save the result to a database. let’s assume that you have a resource /lol/cat/questions you can issue a HTTP post to (you can create this using rubyonrails or something similar).
var CatInformationPanel = Class.create({
initialize: function (container,name) {
this.name = name;
$(container.id+'_furry').checked = true;
$('petButton').observe('click', this.ask.bindAsEventListener(this));
},
ask: function (item) {
var question = "icanhas "+item+" ?"
$(container.id+'_text').value =question;
var request = new Ajax.Request ({
"/lol/cat/question", {
method:'post',
params:{ name:name, question:question },
onSuccess: function (json) {
alert("saved question");
}
}
});
}
});