Mifort Dev Zone is a portal which aim is to track Mifort employees' professional development, provide resources for it and encourage peer-collegue co-operation.
Why I hate&love Angular_Alexey
НАДО НАЙТИ Sergey - http
License: GNU General Public License v3.0
Mifort Dev Zone is a portal which aim is to track Mifort employees' professional development, provide resources for it and encourage peer-collegue co-operation.
Why I hate&love Angular_Alexey
НАДО НАЙТИ Sergey - http
Ждем перевод
Готово, ждет подписи Андрея
While learning JavaScript, you might've heard that JS is a single-threaded language. You also might've heard that JS is asynchronous. These two statements probably left you thinking "Wait, what? JS can't really be asynchronous with just one thread, right?". Let's look into how this works.
Both browsers and Node.js use a runtime engine to run JavaScript (in case of Chrome and Node.js it's the V8). Inside that engine (besides all the other stuff that makes JS actually work) is the stack. Every time a function is called it goes on top of the stack; every time we return from the function (either through return
or by reaching the end of the function) it gets removed from the top of the stack. That basically means that we can only execute one thing at the time. That's pretty bad, considering that the page re-render also happens through the stack and can be blocked, meaning the user won't be able to interact with the page while there's still stuff in the stack.
Luckily, both browsers and Node.js provide us with asynchronous APIs (usually written in C++) that are executed outside of the runtime engine. Whenever an asynchronous call is made (e.g. setTimeout, an AJAX-request or an onClick event) it gets pushed to these APIs, which can run in multiple threads. After that function's execution is finished, its callback handler is placed in the callback queue. This is where the event loop comes into play. Its only job is to check the callback queue every once in a while, and place the next function in the queue on top of the stack whenever the stack is empty and the callback queue isn't.
Here's a visualization of how it all works from Philip Roberts' speech from JSConf EU 2014
What I think should be noted is the way setTimeout actually works. Calling setTimeout(function foo(){...}, 5000)
doesn't mean foo
will be executed in precisely 5 seconds; it means that in 5 seconds foo
will be put into the callback queue, where it will wait until the stack is empty. This is why sometimes setTimeout(..., 0)
is used: instead of just executing its callback immediately, it waits until all the other stuff is done.
While being very similar to its in-browser counterpart, the event loop within Node.js is tad a bit more complex. In Node, the event loop is separated into several phases, each handling it's own operations. These phases are:
setTimeout
and setInterval
by setting thresholds after which they can be executed (but the execution itself is actually handled by the poll phase)setImmediate
and close callbacks)setImmediate
's callbacksclose
events on socketsAnother mechanism Node.js features is the process.nextTick()
function. The way it works is: it accepts a callback and a number of arguments to pass to that callback; it then procedes to invoke the callback before the event loop continues (but still after all synchronous operations) without waiting for the appropriate phase, completely disregarding the event loop's current state. It can cause some serious problems (e.g. if you call it recursively, in which case the event loop will never reach the poll phase, completely disabling I/O), and you might never actually use it in your practice, but it can sometimes prove useful when processing something immediately is essential, or when you need your code to run after everything in the call stack gets processed but before the event loop continues (e.g. if you emit an event before that event's handler is declared you can wrap the emit
function in process.nextTick
so it waits until all everything is declared). For other cases, the official Node.js documentation recommends using setImmediate
instead, since it provides compatibility with in-browser JS and causes less potential problems.
In short, there are some thing in JavaScript that should be done asynchronously, and since the runtime engines are single-threaded, they use other APIs that are capable of working in parallel.
If you're still having trouble understanding how the event loop works or just want to play around with it, there's a resource called loupe (also created by Philip Roberts) that visualizes JavaScript code and shows how the stack, the WebAPIs, the callback queue and the event loop interact with each other.
React is a declarative, component-based JavaScript UI-framework.
React’s core concept is that you page consists of a number of independent components, each with its own state and an array of methods. Components can be defined via JS functions:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
or ES6 classes (which have some additional features), that extend the React.Component
class:
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
Every React component has:
props
object that contains a set of input parameters that are passed to the component through attributes:
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
props
object is read-only, meaning all React components must act like pure functions with respect to their props.state
object, which is local, private and fully controlled by the component and represents the component's state. The only place where you can directly assign the state
is the component's constructor. Component's setState()
method should be used in all other cases. Changing the state via setState()
also causes the component to re-render itself, which is the preferred way to update the view.render()
method that allows you to render the component on a page.render()
should always return a single root element.As you could notice, the render()
methods we used as an example returned a strange HTML-looking thing. This is JSX - a JS syntax extension. JSX can be split into multiple lines, and you can also embed JS expressions in it by wrapping them in singular curly braces. You can create normal HTML using JSX, as well as use any of the components that you've already declared. Any JSX object itself is also a JS expression, therefore it can be assigned to a variable, concatenated with another JSX object, etc.
Note: since JSX is closer to JS than to HTML, the camelCase
attribute naming convention is used, e.g. className
instead of class
.
Finally, ReactDOM has its own render()
method that renders one of your components into an existing element on the page:
ReactDOM.render(
<App />,
document.getElementById('root')
);
To start working with React you will need to:
npm install react react-dom
) or Yarn (yarn add react react-dom
); the react
and react-dom
npm packages also provide single-file distributions in dist folders, which are hosted on a CDN:
<script src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
create-react-app
is also a good way to get started with a new React app, which allows you to create the initial structure for your future application and to optimize your app for production later:
npm install -g create-react-app
create-react-app my-app
cd my-app
npm start
You might've heard about ExpressJS: probably the most popular Node.js framework. You might've also heard the word middleware a whole lot. But what is middleware?
Your standard Express-application usually consists of a bunch of routes (also calles endpoints), as well as a number of handlers for each of these routes, which are executed consecutively. These handlers are called middleware. Now let's go into some detail.
Middleware functions (except for error-handling middleware, we'll cover them later) have access to the request object (req
), response object (res
), as well as the next
middleware function.
Middleware functions can do several things:
req
and res
objectsres.end()
or res.send()
)next
middleware function (if the current middleware function doesn't end the request-response cycle, it should call next()
, or the request will be left hanging)Here's an example: let's have a look at a simple "Hello world" app.
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('Hello World!')
})
app.listen(3000)
The '/' route has a single middleware function that ends the request-response cycle by responding with "Hello world!".
And here's a simple logger function:
const logger = function (req, res, next) {
console.log(req.path);
next()
}
Now, there are multiple ways to add this function as a middleware function. You can:
app.get('/', logger, function (req, res) {
res.send('Hello World!')
})
const rootRouter = express.Router()
//...
const router = express.Router()
router.use('/root', logger, rootRouter)
app.use
):
app.use(logger);
There are several types of middleware:
app.use()
or app.METHOD()
makes it application-level middleware. It's important to note here that the order in which you add application-level middleware to your app matters: as with all types of middleware, application-level middleware will be executed (or checked for, in case of routes) in order it was defined.express.Router()
next()
function (except the string 'route') will skip any remaining non-error-handling middleware an pass control to the first error-handling middleware. Unlike other middleware function, error-handling middleware accept four arguments: err
, req
, res
, next
:
function errorHandler (err, req, res, next) {
if (res.headersSent) {
return next(err)
}
res.status(500)
res.render('error', { error: err })
}
express.static
, which is used to serve static content:
express.static(root, [options])
cookie-parser
, body-parser
).To sum up, middleware functions make Express apps customizable and easy to build by allowing to add stuff like error-handlers, validation, loggers and application logic to both single and multiple routes, as well as increase functionality by adding libraries as midleware functions.
Vue.js is a JavaScript UI framework. Unlike other monolithic frameworks, Vue is designed from the ground up to be incrementally adoptable. The core library is focused on the view layer only, and is easy to pick up and integrate with other libraries or existing projects. Although not as popular as its main competitors - Angular and React - the framework has been gaining popularity due to its simplicity and adoptability.
Vue is a progressive framework. In short, that means Vue has:
Why Vue?
Although not strictly associated with the MVVM pattern, Vue’s design was partly inspired by it. As a convention, the vm
variable is often used to refer to the Vue instance:
var data = { name: 'Nick' }
var vm = new Vue({
el: '#example',
data: data
})
Now you just need an element to bind that instance to:
<div id="example">
Hello, {{ name }}
</div>
and voilà! You've got yourself a Vue app! But wait, there's more to it than that.
By using the $
prefix you can address the instance's fields:
vm.$data === data // true
vm.$el === document.getElementById('example') // true
as well as use the instance methods, such as $watch()
:
vm.$watch('name', function (newVal, oldVal) {
// this callback will be called when `vm.name` changes
})
Each Vue instance also goes through a series of steps during it's initialization, each of these steps has a lifecycle hook associated with it, such as created
, mounted
, updated
and destroyed
:
var vm = new Vue({
data: {
name: 'Nick'
},
created: function () {
// `this` points to the vm instance
console.log('name is: ' + this.name)
}
})
// -> "name is: Nick"
Vue templates use the standard "Mustache" syntax (same as Angular). Vue has a number of convenient directives (also same as Angular), which use the v-
prefix :
<span v-once>This will never change: {{ msg }}</span>
<ul id="example">
<li v-for="item in items"> <!-- v-for directive renders the element once for each item in the items array -->
{{ item.message }}
</li>
</ul>
This one, for example, will not allow the view inside this element to update, even once the msg
changes.
"Mustaches" cannot be used inside HTML attributes, so the v-bind
directive should be used:
<div v-bind:id="dynamicId"></div>
Some directives, such as v-bind
or v-on
accept an argument, which comes after a colon right after the directive's name. Some directives can have modifiers that allow you to do some nifty things, such as .prevent
:
<form v-on:submit.prevent="onSubmit"></form>
that, aside from the action assigned to v-on:submit
, also calls the event.preventDefault()
.
Vue also allows you to define filters, that can be used for text formatting:
new Vue({
// ...
filters: {
capitalize: function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
})
Filters are appended to the end of the JavaScript expression, denoted by the “pipe” symbol.
Several most used directives - v-bind
and v-on
- have shorthands, which are entirely optional, but can save you a bit of time:
<!-- full syntax -->
<a v-bind:href="url"></a>
<!-- shorthand -->
<a :href="url"></a>
<!-- full syntax -->
<a v-on:click="doSomething"></a>
<!-- shorthand -->
<a @click="doSomething"></a>
In-template expressions are very convenient, but they cater for non-complicated operations exsclusively. Putting too much logic into your templates can make them bloated and hard to maintain. That's where computed expressions come into play:
<div id="example">
<p>Original message: "{{ message }}"</p>
<p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
el: '#example',
data: {
message: 'Hello'
},
computed: {
// a computed getter
reversedMessage: function () {
// `this` points to the vm instance
return this.message.split('').reverse().join('')
}
}
})
"What's the difference between computed expressions and methods?" you might ask.
// in component
methods: {
reverseMessage: function () {
return this.message.split('').reverse().join('')
}
}
The thing is, computed properties are cached based on their dependencies. A computed property re-evaluates only in case when some of its dependencies are changed, opposed to methods, which always run the function whenever the re-render occurs.
Components allow you to extend basic HTML elements to encapsulate reusable code.At a high level, components are custom elements that Vue’s compiler attaches behavior to. Use Vue.component()
to register a global component:
<div id="example">
<my-component></my-component>
</div>
// register
Vue.component('my-component', {
template: '<div>A custom component!</div>'
})
// create a root instance
new Vue({
el: '#example'
})
Which will render
<div id="example">
<div>A custom component!</div>
</div>
You can also register a component locally:
new Vue({
// ...
components: {
// <my-component> will only be available in parent's template
'my-component': {
template: '<div>A custom component!</div>'
}
}
})
In order to start working with Vue all you need is to install Vue. You can either use the CDN distributive (Vue is a very lightweight library so it's absolutely fine), or install it via npm install vue
or bower install vue
. Vue provides an official CLI that allows you to quickly set up and easily manage your future project.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.