原型到JQuery转换 – 坚持使用class.create

我是一个试图将代码从原型转换为JQuery的新手。 我正在通过基础知识,但我坚持使用下面的代码。 我已尝试使用jquery范围,但无法解决它。 这是代码,我真的很感激一些帮助。

var SaveForm = Class.create(); SaveForm.prototype = { formId: null, responseText: null, initialize: function(formId) { this.formId = formId; }, sendRequest: function(idform) { var referenceThis = this; $(idform).request( { onSuccess: function(transport) { referenceThis.responseText = transport.responseText; referenceThis.onSuccess(); }, onFailure: function(transport) { referenceThis.responseText = transport.responseText; referenceThis.onFailure(); } }); }, onSuccess: function() { }, onFailure: function() { } } 

jQuery是为DOM,事件处理,Ajax和动画而制作的。 创建“类”不在其范围内。

但是,您可以轻松地将其转换为简单的JavaScript构造函数和原型方法:

 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(){}; 

但是,我不确定您实际需要哪种方法。 jQuery没有request方法,只需使用强大的$.ajax函数和Deferedsfunction来执行Ajax请求。 听起来就像你需要的一样

  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) {…}); 

翻译看起来像这样: – 您不需要使用’Class.create()’ – 在创建新的SaveForm实例时必须使用新的’new’ – 将’referenceThis’更改为_this。

为什么你传递2次formId? 初始化中只有一次应该足够了

 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');