Skip to content

Instantly share code, notes, and snippets.

@mweststrate
Last active October 8, 2019 08:51
Show Gist options
  • Save mweststrate/2789bd206a4e055581ab to your computer and use it in GitHub Desktop.
Save mweststrate/2789bd206a4e055581ab to your computer and use it in GitHub Desktop.
pure rendering over time using MOBservable
// The state of our app
var state = mobx.observable({
nrOfSeats : 500,
reservations : [],
seatsLeft : function() { return this.nrOfSeats - this.reservations.length; }
});
// The UI; a function that is applied to the state
var ui = mobx.computed(function() {
return "\n<div>Seats left: " + state.seatsLeft +
"<hr/>Attendees: " + state.reservations.join(", ") + "</div>";
});
// Make sure the UI is 'rendered' whenever it changes
ui.observe(function(newView) { console.log(newView) }, true);
// Put in some test data
state.reservations[0] = "Michel";
state.reservations.push("You?");
state.reservations[0] = "@mweststrate";
state.nrOfSeats = 750;
@dvdvdmt
Copy link

dvdvdmt commented Oct 8, 2019

@mweststrate thanks for the awesome article and here is a fixed example that works with the latest version of MobX:

// The state of our app
var state = mobx.observable({
  nrOfSeats : 500,
  reservations : [],
  get seatsLeft(){ return this.nrOfSeats - this.reservations.length; }
});

// The UI; a function that is applied to the state
var ui = mobx.computed(function() {
  return `\n<div>Seats left: ${state.seatsLeft}<hr/>Attendees: ${state.reservations.join(", ")}</div>`;
});

// Make sure the UI is 'rendered' whenever it changes
ui.observe(function({newValue}) { console.log(newValue) }, true);

// Put in some test data
state.reservations[0] = "Michel";
state.reservations.push("You?");
state.reservations[0] = "@mweststrate";
state.nrOfSeats = 750;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment