Introduction 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:
// 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.

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

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.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.
