未加星标

Javascript, The Builder Pattern & Callbacks

字体大小 | |
[前端(javascript) 所属分类 前端(javascript) | 发布者 店小二05 | 时间 2018 | 作者 红领巾 ] 0人收藏点击收藏

I'm trying to use Node.js to handle some scriptable URL redirection for me. It's working quite well but the scripts need to be in as simple a format as possible as it will be managed by someone else.

What I'd like to do is use the builder pattern so I can have something along the lines of:

redirectWhen.isMobileDevice().urlMatches("http://www.somewhere.com").thenGoTo("http://mobile.somewhere.com"); redirectWhen.urlMatches("http://subdomain.somewhere.com").thenGoTo("http://www.somewhere.com/somefolder/");

Then I'd redirect based on the results (basically the last one that matched all items in the chain wins). If you imagine all the functions ( isMobileDevice() & urlMatches(...) do some simple string checking & nothing more, then all works fine.

But I need the isMobileDevice() function to perform an HTTP request to something. That means having a callback function that gets called when the response completes. Will it be possible to do this & still keep the builder pattern intact? I imagine I could do something like:

redirectWhen.isMobileDevice(function() { urlMatches("...").thenGoTo("..."); });

But that's adding more complexity to the scripts than I want to. The people who will be managing these scripts know basic javascript but if they have to start nesting callbacks, I imagine they will get confused fast.

I'm guessing I'm trying to achieve something that's not possible here but I don't know enough JS myself to be able to confirm that!

Problem courtesy of: Lee Theobald

Solution

You shouldn't have to give up your elegant building pattern just to make it work asynchronously. You can make a linked list of nodes with each node calling the next node when it succeeds.

I set up a fiddle using a Chain and multiple ChainNode implementations. Some notes:

Each ChainNode has an execute() method and a nextNode which it needs to call using next() when it is done with its own processing. For example, the URL pattern matcher calls the next node only if the URL matches the pattern, else it simply returns (breaking the chain of execution). The IsMobileNode can be implemented by calling next() from a callback to some asynchronous call (such as AJAX). In the fiddle, a simple setTimeout demonstrates the concept. The Chain keeps a head which indicates where the start execution and a tail on which to append new nodes. The chain(nextNode) method makes sure the chain is kept intact. The urlMatches(urlPattern) and isMobileDevice() methods simply create a node and append it to the chain. The thenGoTo() method chains a final node to initiate the redirect. Then, it executes the chain starting from the head .

Solution courtesy of: Mattias Buelens

Discussion

The comment by Dan Lee on my question also helped me come across the Q library: https://github.com/kriskowal/q . That certainly would help with what I wanted, although it's not as simple as the other answers.

Discussion courtesy of: Lee Theobald

It is perfectly possible; your builder returns an intermediate object at each step, and in the last step, you finally put the pieces together and call the final function.

function redirectWhen() { var building = {}; // saved state goes here // actually implement redirection function build() { // expects building = { source: "...", target: "...", mobile: optionalBoolean} if (building.mobile) { checkMobile(); } else { finishBuild(); } } function checkMobile() { // check if actually mobile by making an HTTP request // in the success callback, calls finishBuild - fails otherwise // .. } function finishBuild() { // accessible only if mobile not requested, or if requested and mobile check passed // .. } // prepare the second step var urlMatches = function(url) { building.source = url; return { thenGoTo: function(target) { building.target = target; build(); } } } // return the next steps return { isMobileDevice: function() { builder.mobile = true; return urlMatches; }, urlMatches: urlMatches } }

To support your mobile test, you would split build into two parts (the check, and the callback); but this would be opaque to the user, who does not even know that there is a build function anywhere.

Discussion courtesy of: tucuxi

This recipe can be found in it's original form on Stack Over Flow .

本文前端(javascript)相关术语:javascript是什么意思 javascript下载 javascript权威指南 javascript基础教程 javascript 正则表达式 javascript设计模式 javascript高级程序设计 精通javascript javascript教程

代码区博客精选文章
分页:12
转载请注明
本文标题:Javascript, The Builder Pattern & Callbacks
本站链接:https://www.codesec.net/view/611133.html


1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责;
2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性,不作出任何保证或承若;
3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。
登录后可拥有收藏文章、关注作者等权限...
技术大类 技术大类 | 前端(javascript) | 评论(0) | 阅读(54)