Prototype To JQuery Conversion - Stuck With Class.create
I'm a novice who's trying to convert code from prototype to JQuery. I'm getting through the basics but am stuck with the code below. I've tried using jquery extent but cannot work
Solution 1:
jQuery is made for DOM, Event handling, Ajax and Animation. Creating "classes" is not in its scope.
However, you can easily transform it to a simple plain JavaScript constructor function and prototype methods:
function SaveForm(formId) {
this.formId = formId;
this.responseText = null;
}
SaveForm.prototype.sendRequest = function(idform){
var _this = this;
$(idform).request({
onSuccess: function(transport){
_this.responseText = transport.responseText;
_this.onSuccess();
},
onFailure: function(transport){
_this.responseText = transport.responseText;
_this.onFailure();
}
});
};
SaveForm.prototype.onSuccess = function(){};
SaveForm.prototype.onFailure = function(){};
However, I'm not sure which of these methods you actually need. jQuery has no request
method, and to do Ajax requests just use the powerful $.ajax
function, and the Defereds functionality. Sounds like all you need is
function submitForm(id) {
var $form = $('#'+id);
return $.ajax({
url: $form.attr("target"),
method: $form.attr("method"),
data: $form.serialize(),
dataType: "html"
});
}
// Usage:
submitForm("myForm")
.done(function onSuccess(responseText) {…})
.fail(function onFailure(error) {…});
Solution 2:
The translation would look like that: - you don't need to use 'Class.create()' - you have to use new 'new' when creating a new SaveForm instance - change 'referenceThis' to _this.
Why do you pass 2 times the formId? only once in the initialize should be enough
var SaveForm = function(){
this.formId;
this.responseText;
};
SaveForm.prototype.initialize = function(formId){
this.formId = formId;
}
SaveForm.prototype.sendRequest = function(idform){
var _this = this;
$(idform).request({
onSuccess: function(transport){
_this.responseText = transport.responseText;
_this.onSuccess();
},
onFailure: function(transport){
_this.responseText = transport.responseText;
_this.onFailure();
}
});
};
SaveForm.prototype.onSuccess = function(){};
SaveForm.prototype.onFailure = function(){};
var form = new SaveForm(); // 'new' is very important!!
form.initialize('myId');
Post a Comment for "Prototype To JQuery Conversion - Stuck With Class.create"