在原型中定义处理程序功能

编程入门 行业动态 更新时间:2024-10-22 11:26:28
本文介绍了在原型中定义处理程序功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试创建一个JavaScript原型,该原型将允许我以类似于jQuery ajax调用方式的方式处理流程的结果.例如:

I am trying to create a JavaScript prototype that will allow me to handle the outcome of a process in a similar way to the jQuery ajax call works. For example:

var request = $.ajax({ //params here }) .done(function(data, textStatus, jqXHR) { //action here }) .fail(function (jqXHR, textStatus, errorThrown) { //action here });

我如何声明我的原型具有done和fail事件(如果甚至可以使用正确的术语),并确保它们在原型逻辑内的条件下被触发?

How do I declare my prototype to have the done and fail events (if that is even the correct term to use) and make sure that they are fired under a condition from within the prototype logic?

我想要的呼叫将是这样的:

My desired call would be something like this:

var o = myObj({ parma1: 'a', param2: 'b' }) .done(function() { //action here }); .fail(function() { //action here });

我希望这是有道理的,因为我不知道此过程的正确术语是什么:(

I hope this makes sense as I do not know what the correct terminologies are for this process :(

我正在使用jQuery,因此,如果有使用jQuery的更好的解决方案,那很好.

I am using jQuery so if there is a better solution using jQuery then that is fine.

推荐答案

我想您想将其用于异步任务.这是一个有点类似的解决方案:

I suppose you want to use this for an asyncrhonous task. Here is a somewhat similar solution:

var o = { parma1: 'a', param2: 'b', doAsyncStuff: function(complete, error){ var someData = 0; setTimeout(function(){ someData = 1; complete(someData); }, 500); //or if something went wrong: //error(someErrorData); } } o.doAsyncStuff(function(data){ console.log('complete', data); }, function(data){ console.log('error', data); });

jsfiddle/pA99q/1/

根据要求,使用延迟对象的更新版本.如果可能需要的话,我也允许自己自由添加progress:

As requested, an updated version using deferred objects. I took myself the freedom to include progress as well, in case you might need it:

var task = (function($){ var dfd = $.Deferred(), cls = function(){ console.log('param passed:', arguments); for(var i = 0; i < 5; i++){ var count = 0; setTimeout(function(){ count++; dfd.notify({ msg: 'interation ' + count + ' complete' }); if(count === 5) dfd.resolve({ something: 1 }); //if anything goes wrong, //you can always reject the deferred: //dfd.reject(args); }, 1000 * i); } }; cls.prototype = { done: dfd.promise().done, fail: dfd.promise().fail, always: dfd.promise().always, progress: dfd.promise().progress }; return cls; })(jQuery); var t = new task({ foo: 'bar' }, 123, 'baz'); t.progress(function(data){ console.log('progress:', data); }).done(function(){ console.log('done'); }).fail(function(){ console.log('fail'); }).always(function(){ console.log('always'); });

jsfiddle/hGFbt/

更多推荐

在原型中定义处理程序功能

本文发布于:2023-10-13 00:03:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1486247.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:原型   定义   功能   程序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!