Brook cited the pipe concept under UNIX to easily connect all processes in series to complete the task together. The output of the previous process is used as the input of the next process to complete the parameter transfer. Through brook you can write your javascript program in MVC way.
http://hirokidaichi.github.com/brook/ brook Script Home Download
The brook framework uses the namespace library for module organization.
Here we use an example again to illustrate the use of namespace:
// Define a sample namespace
Namespace('sample')
// Use brook
.use('brook *')
.use('brook.util *')
.define( function (ns) {
var foo = function() {
alert('this is sample.foo');
};
// Define public functions
// As long as the external module uses sample, it can call
ns.provide({
foo : foo
});
}) through ns.sample.foo();
// Example of use
Namespace.use('sample').apply(function(ns) {
ns.sample.foo();
});
To understand the brook framework, you need to understand several core concepts of brook.
promise
To put it simply, promise is an encapsulated function, which is responsible for passing the value to the next promise. It's like passing the baton (value) to the next member (promise) in a relay race. This allows asynchronous processing to be programmed in a sequence similar to synchronous processing.
var p = ns.promise(function(next, value ){
// Process the value here
// The value is passed in from the previous promise
// Hand over the work to the next promise
next("new_value");
});
Then let’s see what promises can do. For example, there is such a requirement
: Wait for one second
: Output moge
: Wait for two seconds
: Output muga
When promise is not used:
(function() {
var firstInterval = setInterval(function() {
console.log("moge");
clearInterval(firstInterval);
var secondInterval = setInterval(function() {
console.log("muga");
clearInterval(secondInterval);
}, 2000);
}, 1000);
})();
This code processing sequence is difficult to understand. If you use promises instead:
Namespace("sample")
.use("brook *")
.use("brook.util *")
.define(function(ns) {
var p1 = ns.promise(function(next, value ) {
console.log("moge");
next("muga");
});
var p2 = ns.promise(function(next, value) {
console.log(value);
next();
});
ns.provide({
execute: function() {
ns.wait(1000).bind(p1 ).bind(ns.wait(2000)).bind(p2).run();
}
});
});
Namespace.use("sample").apply (function(ns) {
ns.sample.execute();
});
The bind function can accept multiple parameters and can also be written like this:
ns .wait(1000).bind(p1, ns.wait(1000), p2).run();
How to use promise:
1: Wait for a few seconds and you can use the wait method under brook.util
2: The "stick handover" between promises is achieved through the bind method, which is the PIPE function under UNIX.
3: Finally, you need to execute the run() method
channel
channel, as the name suggests, means channel and pipeline. In brook it represents a collection of promises. Multiple promises can be stored in a channel and then executed together.
var p3 = ns.promise(function(next, value ) {
console.log(value "!");
});
var p4 = ns.promise(function(next, value) {
console.log(value "!!" );
});
ns.provide({
execute: function() {
var channel = ns.channel("testChannel");
channel.observe(p3);
channel.observe(p4);
ns.sendChannel("testChannel").run("hello");
}
});
How to use channel:
1: observer: append promise to channel
2: sendChannel: determine channel
3: Finally, run all promises in the channel
model
Model is a package of channels. In the model, you can define channels with names, and these channels are methods one by one.
This component can clarify the M and V in MVC, that is, the module and the view. It can write such processing. After the model's method is executed, its results are passed to one or more views (promise). This is the observer pattern.
var requestFilter = ns.promise(function(v){
v["viewer_id"] = viewer.getID();
retrun v;
});
var create = ns.promise(function(n,v){
// get data
n(response);
});
var delete = ns.promise(function(n,v){
// get data
n(response);
});
var view1 = ns.promise(function(n,v){
// render html
n(v);
});
var view2 = ns. promise(function(n,v){
// render html
n(v);
});
var model = ns.createModel();
model.addMethod(' create', ns.mapper(requestFilter).bind(create));
model.addMethod('delete', ns.mapper(requestFilter).bind(delete));
ns.from(model.method ('create')).bind(view1).run();
ns.from(model.method('create')).bind(view2).run();
ns.promise() .bind(model.notify('create').run({"body": "test"}));
//Pass parameters {"body": "test"} to view1 and view2
How to use model:
: ns.createModel(): Generate model
: model.addMethod(): Define method name and corresponding processing promise
: ns.from(): Definition Processing after a certain method of the model is executed
: model.notify(): Execute the method of the model
widget
The widget is responsible for associating the html with the namespace module. Let's look at a simple example.
First define a namespace of sample.widget.
// sample-widget.js
Namespace( "sample.widget")
.use("brook.widget *")
.define(function(ns) {
ns.provide({
registerElement: function(element) {
element.innerHTML = "Hello World!";
}
});
});
The following is the html page about sample.widget.
> ;
widget
This code will replace all the div contents of the data-widget-namespace specified as sample.widget with hello world!
The difference between run() and subscribe()
promise execution You need to use the run() method. When a callback function needs to be executed after a promise chain is processed, do not use run but use subscribe.
ns.promise().bind(function(next, value) {
next(value);
}).subscribe(function(value) {
console.log(value, "world!");
}, "hello");
//hello world!
ns.promise().bind(function(next, value) {
console.log(value);
next("no next");
} ).run("hello");
//hello
brook.util
This module defines many useful methods.
mapper: Define decoration processing
var input = ns.promise(function(next, value) {
next("this is input");
});
var mapper = ns.mapper(function( value) {
return value "!";
});
var output = ns.promise(function(next, value) {
console.log(value);
next( value);
});
//Execute
input.bind(mapper).bind(output).run();
//this is input!
filter: filter
var input = ns.promise (function(next, value) {
next(2);
});
var evenFilter = ns.filter(function(value) {
return (value % 2) === 0 ;
});
var output = ns.promise(function(next, value) {
console.log(value " is even");
next(value);
} );
//Execute
input.bind(evenFilter).bind(output).run();
//2 is even
scatter: scatterer, value The values inside call the next promise in sequence
var output = ns .promise(function(next, value) {
console.log(value);
next(value);
});
//Execute
ns.scatter().bind (output).run([1, 2, 3, 4, 5, 6]);
//1
//2
//3
//4
// 5
//6
takeBy: Take n items at a time from value and call the next promise
var output = ns.promise(function(next, value) {
console.log(value);
next(value);
});
//実行
ns.scatter().bind(ns.takeBy(2)).bind(output).run([1, 2, 3, 4, 5, 6] );
//[1, 2]
//[3, 4]
//[5, 6]
wait: wait n milliseconds
cond : Conditionally execute promise, the first parameter is the filter, and the second parameter is the promise. When the first parameter is true, the promise of the second parameter is executed.
var output = ns.promise(function(next, value ) {
console.log(value);
next(value);
});
var isEven = function(num) {
return (num % 2 === 0) ;
};
var done = ns.promise(function(next, value) {
console.log("done");
});
//実行
ns.cond(isEven, output).bind(done).run(2);
//2
//done
ns.cond(isEven, output).bind(done).run( 3);
//done
match: Determine which promise to execute based on the value of value.
var dispatchTable = {
"__default__": ns .promise(function(next, value) {
console.log("default");
}),
"hello": ns.promise(function(next, value) {
console .log("hello");
}),
"world": ns.promise(function(next, value) {
console.log("world");
})
};
ns.match(dispatchTable).run("hello");
ns.match(dispatchTable).run("world");
ns.match(dispatchTable).run( "hoge");
from: Pass initial parameters for the promise chain, or you can use run to pass them.
ns.from("hello").bind(ns .debug()).run();
//debug: hello
Finally, you can also experience how brook implements the MVC pattern through the example on the github homepage.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version
SublimeText3 Linux latest version

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version
God-level code editing software (SublimeText3)