Monday, April 27, 2015

JavaScript setters and CustomEvent versus "Canned" Observables for MVVM

Most modern browsers now support JavaScript's setter syntax for objects as well as CustomEvent dispatches.  This opens the door to home-brew a simple observable pattern when, for whatever reason, a library offering "canned" observable patterns (like knockout.js or backbone.js) isn't available.

And why wouldn't an mvvm library be available?  In my experience, this can happen because a client or other decision maker rationally or irrationally forbids certain .js libraries.  Or maybe your page really is super-simple (they all start they way...) and doesn't warrant the overhead of full blown mvvm library. want an mvvm framework to work exactly as you want it you build your own!

First, a simple example of setter syntax, which allows you to act whenever something is assigned to a particular property of your object.  All we're going to do for now is log the occurrence:

var x = {
    set b(myval) {
       console.log("b was assigned something!");
       this._b = myval;
    get b() {
       return this._b;

x.b = 7;
console.log("b is " + x.b);
console.log("_b is " + x._b);


b was assigned something!
b is 7
_b is 7

Now let's take it just a step further and raise and event at the document level for which we can listen and act:

var y = {_b:5,
set b(myval) {
this._b = myval;
document.dispatchEvent( new CustomEvent('b_set', { 'detail': this._b }));
  get b() {return this._b;},

document.addEventListener('b_set',function(e) {
console.log("b_set event heard! b is : " + e.detail);



b_set event heard! b is : 7

This basic pattern can be the foundation for an observable pattern that fits your particular situation.  There are a lot of creative things you can do with event names, the event detail object, custom element attributes, etc. to make your own little (or not so little) custom mvvm framework.

No comments:

Post a Comment