Object.watch: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/watch
Object.observe: http://wiki.ecmascript.org/doku.php?id=harmony:observe
They both seem do the same thing at a high level. What are the salient differences between them?
There are many difference.
Microtasks vs synchronous callbacks
One difference is that Object.observe makes callbacks when you enter the message loop. I.e. many changes to the object results in a single callback with all changes rather than multiple callbacks.
When listening to changes on the DOM, the mutation events was replaced with mutation observers for the same reason. The microtask solution is simply more performant than the synchronous callback.
Standard vs non-standard
In addition, Object.observe is a suggested Ecmascript standard for Ecmascript 7. I.e. it is a proposed Javascript standard.
Intent
Object.observe is intended as a performant way to monitor changes to an entire object and the use case is expected to entail listening to many objects. This is a requirement for binding frameworks (i.e. client side templating) such as AngularJs and Polymer. Object.watch is more a Firefox feature to monitor a specific property and is sprung out of a debugger feature.
Related
Does the EcmaScript specification place any constraints on the process model used to implement the runtime?
For example, is the event loop required to be on a separate thread from the thread managing the runtime communication with the operating system IO subsystems?
No, it does not specify anything about those. Runtime communication and IO are not even part of the language, they come as implementation-dependent exotic objects.
The ECMAScript specification does not even use the term "event loop", though it does define Jobs and Job Queues which work similar. There is no reason however to implement those with multiple threads, after all, JS alone always runs sequentially.
In contrast, the HTML5 spec does define event loops and even a process model, but there is no requirement about multithreading either.
To be clear, I'm hoping for factual information to be presented about RxJS and how it relates to JavaScript's evolution, not a matter of opinion on how good RxJS is, etc.
My question is: is RxJS ( https://github.com/Reactive-Extensions/RxJS ) somewhat of a forward-looking polyfill because of Object.observe, etc. not being standard among browsers yet, or does it fundamentally offer things beyond the scope of what native JS offers and beyond what JS standards seek to offer in the foreseeable future? (Granted, perhaps someday native JS may be capable of X, Y, Z that aren't currently on the radar; I'm not interested in guesses on those.) Perhaps it's a combo.
My motivation/interest in the question is in considering the investment of learning and implementing RxJS in applications, weighed against the timeline of native JS solutions being available, and/or whether there are other considerations to be mentioned that I have not touched on here.
RxJS was birthed as a JavaScript port of Rx.NET. It is not a forward looking polyfill of Object.observe.
RxJs is a library for working with asynchronous operations, with special emphasis on multi-valued operations. The library gives the developer a common "language" they can use to write functional code to manipulate asynchronous streams no matter the stream source. The same "language" works with any combination of UI events, timer events, object mutation observations, animation frames, ajax calls, websocket messages, webworker messages, promises, etc
Object.observe is a mechanism to observe changes in an object. RxJS does not provide this functionality. But RxJS complements this functionality: As an object is changed over time, it can be thought of as a source of asynchronous object change notifications. It is fairly straight-forward to convert these observations into an RxJS source, (e.g. something like Rx.Observable.observeObject(someObject)), which would then let you work with object changes as just another asynchronous RxJs stream with all of the vast array of tools RxJS makes available to you.
RxJs is the library which helps us to do Reactive Programming.
Reactive Programming is a pattern of development that works with asynchronous data stream created of UI Events, HTTP Requests, File System, cache etc. So data stream is an ongoing event sequence in time orderly manner. The stream can emit value, error, and status signal.
Observables are to watch these streams and trigger function on anything occurs in the stream. Observers can subscribe to observables.
Ref- http://technobelities.blogspot.in/2017/02/rxjs-quick-start.html
As per MSDN -
Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators. Reactive Extensions represents all these data sequences as observable sequences. An application can subscribe to these observable sequences to receive asynchronous notifications as new data arrive.
are there any javascript libraries which provide promises and futures syntactically similar to that of C++ ones. basically we want to use them in webworkers, I dont want a callback interface. I want the webworker to block on a future and continue when the UI thread sets the value of the future. i have looked at every possible promise and future library but every thing expects a callback, our code is already a mess and we dont want to further complicate it.
http://code.google.com/p/google-caja/source/browse/trunk/src/com/google/caja/ses-promise.js
Implementation of promises for SES/ES5. Exports Q to the global scope.
Mostly taken from the ref_send implementation by Tyler Close, with the addition of a trademark table to support promises for functions.
Btw, Mark Miller is working on codifying JavaScript's concurrency model and adding eventual send semantics with syntactic sugar for a future version of the language. From http://wiki.ecmascript.org/doku.php?id=strawman:concurrency
Reality: Codifying and formalizing JavaScript’s de-facto concurrency model as a de-jure model.
Promises: A way to (Q(p).post(), Q(p).get()) Make asynchronous requests of objects that may not be synchronously reachable, such as remote objects. (Q(p).when()) Ease the burden of local event loop programming, by reifying the ability to register a callback as a first class value. (Q.async, yield:) for implicit registration of shallow continuations on promises.
Syntactic sugar. The infix “!” operator: An eventual analog of “.“, for making eventual requests look more like immediate requests.
(Q.makePromise()) A promise extension mechanism, so that promise handlers can turn local promise operations into remote messages.
Transport independence: Using remote object messaging as a symmetric abstraction layer, hiding the annoying differences among the various transports listed above as well as server-to-server TCP and UDP transports.
(Vat()) An event-loop spawning mechanism for spawning new event loops that run concurrently with the event loop which spawned it.
Worker independence: Using Vat API as an abstraction layer around worker spawning on the browser or process spawning on the server.
(Vat.evalLater(), where()) Using JavaScript itself as mobile code, so event loops can safely inject new behavior into other event loops
Symmetric Mobile Code: Generalizes from the current use of JavaScript as mobile code sent only from server and only to browsers.
Async-PGAS: Provides a distributed analog to the expressiveness of The Asynchronous Partitioned Global Address Space Model.
There are lots of DOM/CSS inconsistencies between browsers. But how many core JS differences are there between browsers? One that recently tripped me up is that in Firefox, setTimeout callback functions get passed an extra parameter (https://developer.mozilla.org/en/window.setTimeout).
Also, now that browsers are implementing new functions (e.g. Array.map), it can get confusing to know what you can/can't use if you are trying to write code that must work on all browsers (even back to IE6).
Is there a website that cleanly organizes these types of differences?
I find QuirksMode and WebDevout to have the best tables regarding CSS and DOM quirks. You can bridge those incompatibilities with jQuery. There is also this great list started by Paul Irish which includes pretty much any polyfill you could ever need, including ones for ES5 methods such as Array.map.
There doesn't appear to be anything out there that clearly outlines all these issues (very surprising actually). If you use jQuery there is a nice browser compatibility doc section that outlines supported browsers and known issues. I just deal with issues as they come up (as you should be browser testing in all cases anyways) and you can document them if you want to make sure you are coding correctly or if you run into issues and need to know fixes. It's easy to find issues when you do a quick search on a particular topic.
Well, I'm going to open up a CW:
Prior to Firefox 4 Function.apply only accept an Array, not an array-like object. Ref MDC: Function.apply
Some engines (which ones?) promote the result of String.prototype methods from string to String. Ref a String.prototype's "this" doesn't return a string?
Firefox 4 may insert "event loops" into seemingly synchronous code. Ref Asynchronous timer event running synchronously ("buggy") in Firefox 4?
Earlier Firefox versions would accept a trailing , in object literals. Ref trailing comma problem, javascript (Seems "fixed" in FF6).
Firefox and IE both treat function-expression productions incorrectly (but differently).
Math.round/Math.toFixed. Ref Math.round(num) vs num.toFixed(0) and browser inconsistencies
The IE vs. W3C Event Model -- both are missing events/features of the other.
I came across the below posts about custom event handling in JavaScript. From these articles, there are two ways (at least) of handling/firing custom events:
Using DOM methods (createEvent, dispatchEvent)
How do I create a custom event class in Javascript?
http://the.unwashedmeme.com/blog/2004/10/04/custom-javascript-events/
Custom code
http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/
http://www.geekdaily.net/2008/04/02/javascript-defining-and-using-custom-events/
But what is the recommended way of handling (firing & subscribing) custom events?
[Edit] The context for this question is not using any libraries like jQuery, YUI,... but just plain JavaScript
[Edit 2] There seems to be a subtle differences, at least with the error handling.
Dean Edwards ( http://dean.edwards.name/weblog/2009/03/callbacks-vs-events/ ) is recommending the former way for custom event handling. Can we say this a difference?
What your describing is the difference between
A custom event based message passing system
manually firing DOM events.
The former is a way to use events for message passing. An example would be creating an EventEmitter
The latter is simply a way to use the browsers build in DOM event system manually. This is basically using the DOM 3 Event API which natively exists in (competent / modern) browsers.
So the question is simply what do you want to do? Fire DOM events or use events for message passing?
Benchmark showing DOM 3 custom events is 98% slower
The DOM appears to have a huge overhead. It does so because it supports event propagation and bubbling. It does because it supports binding events to a DOMElement.
If you do not need any of the features of DOM3 events then use a pub/sub library of choice.
[Edit 2]
That's all about error handling, how you do error handling is upto you. If you know your event emitter is synchronous then that's intended behaviour. Either do your own error handling or use setTimeout to make it asynchronous.
Be wary that if you've made it asynchronous you "lose" the guarantee that the event handlers have done their logic after the emit/trigger/dispatch call returns. This requires a completely different high level design then the assumption that event emitters are synchronous. This is not a choice to make lightly
There are pros and cons to each. Use what suits you.
The most obvious "con" to using the DOM methods is that they're tied to browser-based deployments and involve the DOM in things even if it doesn't really make sense (e.g., the messaging isn't related to DOM objects), whereas a standard Observer-style implementation can be used in any environment, not just web browsers, and with any generic object you like.
The most obvious "con" to doing your own Observer implementation is that you've done your own Observer implementation, rather than reusing something already present (tested, debugged, optimised, etc.) in the environment.
Many libraries already provide a way to deal with events, and I would recommend on just using an existing library. If you use the DOM, you are assuming that the browser provides the necessary support, whereas if you use a custom mechanism, you might be sacrificing speed for the custom implementation. If you rely on an existing library, the library can choose the appropriate tradeoffs.
For example, Closure provides EventTarget which has an interface simliar to that of the DOM mechanism, but which does not depend on the browser to provide native support for it.