search
HomeWeb Front-endJS TutorialNode.js framework ThinkJS development controller explanation

Original: Jingxiu.com web page instant push | Please indicate the source for reprinting
Link:

This series of tutorials is based on ThinkJS v2.x version (official website) Examples are introduced, and the tutorial focuses on practical operations.

This article continues to explain the use of Controller.

Constructor method

If you want to do something when the object is instantiated, the constructor method is the best choice. The constructor provided by ES6 is constructor.

The constructor method is the default method of the class. This method is automatically called when an object instance is generated through the new command. A class must have a constructor method. If not explicitly defined, an empty constructor method will be added by default.
Method
ECMAScript 6 Getting Started Author: Ruan Yifeng

init and constructor

The power of thinkjs is that we can not only follow the rules The export default class declares Class by itself, and also provides a method to dynamically create Class: think.controller.

But the Class dynamically created by thinkjs does not have a constructor, but provides an init as an alternative to the constructor method, which is used in the same way as the constructor Consistent.

The previous article (Node.js Domestic MVC Framework ThinkJS Development Controller Chapter Base Class and Inheritance Chain Part) also has examples of the use of the init method, look at the code again:


// src/home/controller/base.js'use strict';export default class extends think.controller.base {
  init(...args) {super.init(...args);// 要求全部 url 必须携带 auth 参数let auth = this.get('auth');if (think.isEmpty(auth)) {  return this.error(500, '全部 url 必须携带 auth 参数');}
  }}

Of course, this does not mean that you cannot use the constructor method. If you are like me, you are used to using export default class to declare the Class yourself. You can still use the standard constructor method.

For the method of dynamically creating Class in thinkjs, please refer to the official documentation and will not be repeated here.

Magic method

thinkjs has implemented several very useful magic methods, which provides great convenience for development. Manually like ~

__before pre- Operation

As the name suggests, the pre-operation will be executed before the specific Action in the Controller is executed, which means "executed before xxx". Let’s look at the code:


// src/home/controller/user.js'use strict';export default class extends think.controller.base {
  __before() {console.log('this is __before().');
  }
  indexAction() {console.log('this is indexAction().');return this.end();
  }}// 访问 /home/user/index 的执行结果如下:// this is __before().// this is indexAction().

Then someone may say: It seems that __before has the same purpose as init. As usual, let’s look at the code:


// src/home/controller/user.js'use strict';export default class extends think.controller.base {
  init(...args) {super.init(...args);console.log('this is init().');
  }
  __before() {console.log('this is __before().');
  }
  indexAction() {console.log('this is indexAction().');return this.end();
  }}// 访问 /home/user/index 的执行结果如下:// this is init().// this is __before().// this is indexAction().

Do you see it? There is still a sequence of execution, here is a more complicated one:


// src/home/controller/base.js'use strict';export default class extends think.controller.base {
  init(...args) {super.init(...args);console.log('this is base.init().');
  }}// src/home/controller/user.js'use strict';export default class extends think.controller.base {
  init(...args) {super.init(...args);console.log('this is user.init().');
  }
  __before() {console.log('this is user.__before().');
  }
  indexAction() {console.log('this is user.indexAction().');return this.end();
  }}// 访问 /home/user/index 的执行结果如下:// this is base.init().// this is user.init().// this is user.__before().// this is user.indexAction().

Okay, you would say "expected"~

__after Operation

After understanding the pre-operation, the post-operation is not difficult to understand. Look at the code:


// src/home/controller/user.js'use strict';export default class extends think.controller.base {
  init(...args) {super.init(...args);console.log('this is init().');
  }
  __before() {console.log('this is __before().');
  }
  __after() {console.log('this is __after().');
  }
  indexAction() {console.log('this is indexAction().');return this.end();
  }}// 访问 /home/user/index 的执行结果如下:// this is init().// this is __before().// this is indexAction().

Eh? Something seems wrong. . . __after Not executed.

Of course this is not caused by __after written above indexAction! Modified code:


// src/home/controller/user.js'use strict';export default class extends think.controller.base {
  init(...args) {super.init(...args);console.log('this is init().');
  }
  __before() {console.log('this is __before().');
  }
  __after() {console.log('this is __after().');return this.end();
  }
  indexAction() {console.log('this is indexAction().');
  }}// 访问 /home/user/index 的执行结果如下:// this is init().// this is __before().// this is indexAction().// this is __after().

This time it’s OK, consistent with the expected results.

I know that you have noticed that the code return this.end() has been moved from indexAction to __after.

this.end() Internally performs the Node.js HTTP response.end() operation, indicating that the entire response stream is over, so if you want to enable # If ##__after, this code must be run in __after.

__call No operation

This magic method is a bit special. It is not used to run at a certain process node like the previous two magic methods, but it is shared with

init## Part of #'s responsibilities: used to detect when a Controller is accessed by an Action that is not defined, and __call will take over the operation.

// src/home/controller/user.js'use strict';export default class extends think.controller.base {
  init(...args) {super.init(...args);console.log('this is init().');
  }
  __call() {console.log(this.http.action + 'Action is not exists.');return this.end();
  }
  indexAction() {console.log('this is indexAction().');return this.end();
  }}// 访问 /home/user/test 的执行结果如下:// this is init().// testAction is not exists.

You can see that when the accessed

testAction

does not exist, the framework will run __call for processing, our processing Yes logs the error and ends the response output. The sample code places

__call

in the second-level subclass, usually in the base class, which can control the illegal access processing of all subclasses.

Tip: This method can only be used to capture the situation when the Action does not exist, but if the Controller does not exist, it will directly trigger a 404 error (taken over by the framework) and cannot interfere.
If you want to capture the situation when the Controller does not exist, you need to extend the error class of the framework, which will be described in another article.


External calling method

The thinkjs official website API has an interface for instantiating another Controller, but it does not explain the specific use of this:

//实例化 home 模块下 user controllerlet instance = think.controller('user', http, 'home');

Then usually this method can be used to instantiate a sibling-level Controller, or obtain data, or trigger a business process, etc. Let’s look at the code:

// src/home/controller/user.js 增加_getPoints() {
  return 8000;}// src/home/controller/index.jslet instance = think.controller('user', this.http, 'home');let points = instance._getPoints();console.log(points); // 打印:8000instance.indexAction(); // 与直接执行 /home/user/index 是一样的效果instance.testAction(); // 报错 [Error] TypeError: instance.testAction is not a function

It can be seen that thinkjs provides a way to instantiate a Controller on demand and run its methods.

At first glance, this method is very close to the running result of

this.redirect

(except for the magic method that does not trigger __call), so what does thinkjs provide with this method? What to use? Let’s look at the code: <p class="sourceCode"><br></p><pre class='brush:php;toolbar:false;'>// src/home/controller/util.js&amp;#39;use strict&amp;#39;;export default class extends think.controller.base { calcGPSDistance(lat, lng){// 计算 GPS 两点直线距离return distance; } calcBaiduDistance(lat, lng){// 计算 百度大地坐标 两点直线距离return distance; } calcSosoDistance(lat, lng){// 计算 Soso坐标 两点直线距离return distance; }}</pre><p>这是一个助手 Controller,一个“隐身”的 Controller,从 url 是无法直接访问到的,因为它的所有方法名均没有 Action 后缀。</p> <p>这个场景下,运行时实例化 Controller 并操作其方法的方式就派上用场了。</p> <h2 id="内置-http-对象">内置 http 对象</h2> <blockquote><p>控制器在实例化时,会将 http 传递进去。该 http 对象是 ThinkJS 对 req 和 res 重新包装的一个对象,而非 Node.js 内置的 http 对象。<br>Action 里如果想获取该对象,可以通过 this.http 来获取。<br><br><em>thinkjs 官网</em></p></blockquote> <h2 id="扩展应用-增加一个-n-秒后自动跳转的过渡页功能">扩展应用:增加一个 n 秒后自动跳转的过渡页功能</h2> <p>thinkjs 框架并没有给我们准备这样一个过渡页面的功能,那么我们可以自己实现一个来练练手,上代码:</p> <p class="sourceCode"><br></p><pre class='brush:php;toolbar:false;'>// src/common/controller/complete.js&amp;#39;use strict&amp;#39;;export default class extends think.controller.base { /** * 显示中转页面 * * 调用方式: * let complete = think.controller(&amp;#39;complete&amp;#39;, this.http, &amp;#39;common&amp;#39;); * return complete.display(&amp;#39;应用新增成功!&amp;#39;, &amp;#39;/&amp;#39;, 5); * * @param msg 提示文字,支持 HTML * @param url 后续自动跳转的目标地址 * @param delay 停留秒数 * @returns {think.Promise} */ display(msg, url=&amp;#39;&amp;#39;, delay=3) {let tpl = &amp;#39;common/complete/200&amp;#39;;let opt = think.extend({}, {type: &amp;#39;base&amp;#39;, file_depr: &amp;#39;_&amp;#39;, content_type: &amp;#39;text/html&amp;#39;});this.fetch(tpl, {}, opt).then(content =&gt; { content = content.replace(/COMPLETE_MESSAGE/g, msg); if (url) {content = content.replace(/TARGET_URL/g, url);content = content.replace(/WAIT_SECONDS/g, delay); }; this.type(opt[&amp;#39;content_type&amp;#39;]); return this.end(content);}).catch(function(err){ return this.end(&amp;#39;&amp;#39;);}); }}</pre><p class="sourceCode"><br></p><pre class='brush:php;toolbar:false;'>&lt;!-- view/common/complete_200.html --&gt;&lt;!DOCTYPE html&gt;&lt;html&gt;&lt;head&gt;&lt;title&gt;正在跳转 - 荆秀网&lt;/title&gt;&lt;/head&gt;&lt;body&gt;&lt;p class=&quot;header&quot;&gt;&lt;p class=&quot;wrap&quot;&gt;&lt;p class=&quot;logo&quot;&gt;&lt;a href=&quot;/&quot;&gt;&lt;img src=&quot;/static/imghwm/default1.png&quot; data-src=&quot;/static/img/logo.png&quot; class=&quot;lazy&quot; alt=&quot;XxuYou&quot; style=&quot;max-width:90%&quot;&gt;&lt;/a&gt;&lt;/p&gt;&lt;p class=&quot;headr&quot;&gt; &lt;/p&gt;&lt;/p&gt;&lt;/p&gt;&lt;p class=&quot;wrap&quot;&gt;&lt;p style=&quot;margin-top:20px;height:100px;background:url(/static/img/200.gif) top center no-repeat;&quot;&gt;&lt;/p&gt;&lt;h1 id=&quot;COMPLETE-MESSAGE&quot;&gt;COMPLETE_MESSAGE&lt;/h1&gt;&lt;p class=&quot;error-msg&quot;&gt;&lt;pre class=&quot;brush:php;toolbar:false&quot;&gt;提示:页面将在 &lt;span id=&quot;_count&quot;&gt;WAIT_SECONDS&lt;/span&gt; 秒后重定向到 &lt;a href=&quot;TARGET_URL&quot;&gt;TARGET_URL&lt;/a&gt;</pre>

<script>var thisLoad = function () {var _target_url = document.getElementById(&#39;_target_url&#39;).value;var _wait_seconds = document.getElementById(&#39;_wait_seconds&#39;).value;if (_target_url == &#39;&#39;) return false;if (/^\d+$/.test(_wait_seconds) == false || _wait_seconds < 1 || _wait_seconds >= 3600) {try {document.location.replace(_target_url);} catch(e) {};} else {thisCount(_wait_seconds);window.setTimeout(function () {try {document.location.replace(_target_url);} catch(e) {};}, _wait_seconds*1000);};return true;};var thisCount = function (cnt) {if (cnt < 0) return false;document.getElementById(&#39;_count&#39;).innerHTML = cnt;window.setTimeout(function () {thisCount(--cnt);}, 1000);};window.attachEvent ? window.attachEvent(&#39;onload&#39;, thisLoad) : window.addEventListener(&#39;load&#39;, thisLoad);</script>

The above is the detailed content of Node.js framework ThinkJS development controller explanation. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),