search
HomeWeb Front-endJS TutorialIntroduction to brook javascript framework_js object-oriented

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:

Copy the code The code is as follows:

// 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.
Copy code The code is as follows:

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:
Copy code The code is as follows:

(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:
Copy code The code is as follows:

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.
Copy code The code is as follows:

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.
Copy code The code is as follows:

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.
Copy code The code is as follows:

// 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.
Copy code The code is as follows:



widget sample


> ;


widget


hoge

foo

bar





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.
Copy code The code is as follows:

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
Copy code The code is as follows:

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
Copy code The code is as follows:

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
Copy code The code is as follows:

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
Copy code The code is as follows:

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.
Copy code The code is as follows:

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.
Copy code The code is as follows:

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.
Copy code The code is as follows:

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.
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

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: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

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 Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

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.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

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.

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SecLists

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 new version

SublimeText3 Linux latest version

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MinGW - Minimalist GNU for Windows

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

SublimeText3 Mac version

God-level code editing software (SublimeText3)