Tag: Reactive

Reactive jQuery for Spaghetti-fied Legacy Codebases (or When You Can’t Have Nice Things)

I can hear you crying out now: “Why on Earth would you want to use jQuery when there are much better tools available? Madness! What sort of maniac are you?” These are reasonable questions, and I’ll answer them with a little bit of context.

In my current job, I am responsible for the care and feeding of a legacy website. It’s old. The front-end relies on jQuery, and like most old legacy systems, it’s not in the best shape. That alone isn’t the worst, but I’m working with additional constraints. For example, we’re working on a full rewrite of the system, so massive refactoring work isn’t being approved, and I’m also not permitted to add new dependencies to the existing system without a full security review, which historically can take up to a year. Effectively, jQuery is the only JavaScript library I can use, since it’s already there. 

My company has only recently come to realize that front-end developers might have important skills to contribute, so the entire front end of the app was written by developers unaware of best practices, and often contemptuous of their assignment. As a result, the code quality is wildly uneven and quite poor and unidiomatic overall.

Yeah, I work in that legacy codebase: quintessential jQuery spaghetti.

Someone has to do it, and since there will always be more legacy code in the world than greenfield projects, there will always be lots of us. I don’t want your sympathy, either. Dealing with this stuff, learning to cope with front-end spaghetti on such a massive scale has made me a better, if crankier, developer.

So how do you know if you’ve got spaghetti jQuery on your hands? One reliable code smell I’ve found is a lack of the venerable old .toggle(). If you’ve managed to successfully not think about jQuery for a while, it is a library that smooths cross-browser compatibility issues while also making DOM queries and mutations incredibly easy. There’s nothing inherently wrong with that, but direct DOM manipulation can be very hard to scale if you’re not careful. The more DOM-manipulation you write, the more defensive against DOM mutation you become. Eventually, you can find yourself with an entire codebase written that way and, combined with less-than-ideal scope management, you are essentially working in an app where all of the state is in the DOM and you can never trust what state the DOM will be in when you need to make changes; changes could swoop in from anywhere in your app whether you like it or not. Your code gets more procedural, bloating things up with more explicit instructions, trying to pull all the data you need from the DOM itself and force it into the state you need it to be in.

This is why .toggle() is often the first thing to go: if you can’t be sure whether an element is visible or not, you have to use .show() and .hide() instead. I’m not saying .show() and .hide() should be Considered Harmful™, but I’ve found they’re a good indication that there might be bigger problems afoot.

What can you do to combat this? One solution my coworkers and I have found takes a hint directly from the reactive frameworks we’d rather be using: observables and state management. We’ve all found that hand-rolling state objects and event-driven update functions while treating our DOM like a one-way dataflow template leads to more predictable results that are easier to change over time.

We each approach the problem a little differently. My take on reactive jQuery is distinctly flavored like Vue drop-in and takes advantage of some “advanced” CSS.

If you check out the script, you’ll see there are two different things happening. First, we have a State object that holds all of the values for our page, and we have a big mess of events.

var State = {   num: 0,   firstName: "",   lastName: "",   titleColor: "black",   updateState: function(key, value){     this[key] = value;              $  ("[data-text]").each(function(index, elem){       var tag = $  (elem).attr("data-tag");       $  (elem).text(State[tag]);     });          $  ("[data-color]").each(function(index, elem){       var tag = $  (elem).attr("data-tag");       $  (elem).attr("data-color", State[tag]);     });   } };

I’ll admit it, I love custom HTML attributes, and I’ve applied them liberally throughout my solution. I’ve never liked how HTML classes often do double-duty as CSS hooks and JavaScript hooks, and how if you use a class for both purposes at once, you’ve introduced brittleness into your script. This problem goes away completely with HTML attributes. Classes become classes again, and the attributes become whatever metadata or styling hook I need.

If you look at the HTML, you’ll find that every element in the DOM that needs to display data has a data-tag attribute with a value that corresponds to a property in the State object that contains the data to be displayed, and an attribute with no value that describes the sort of transformation that needs to happen to the element it’s applied to. This example has two different sorts of transformations, text and color.

<h1 data-tag="titleColor" data-color>jDux is super cool!</h1>

On to the events. Every change we want to make to our data is fired by an event. In the script, you’ll find every event we’re concerned about listed with its own .on() method. Every event triggers an update method and sends two pieces of information: which property in the State object that needs to be updated, and the new value it should be set to.

$  ("#inc").on("click", function(){   State.updateState("num", State.num + 1) });  $  ("#dec").on("click", function(){   State.updateState("num", State.num - 1) });  $  ("#firstNameInput").on("input", function(){   State.updateState("firstName", $  (this).val() ) });  $  ("#lastNameInput").on("input", function(){   State.updateState("lastName", $  (this).val() ) });  $  ('[class^=button]').on("click", function(e) {   State.updateState('titleColor', e.target.innerText); });

This brings us to State.updateState(), the update function that keeps your page in sync with your state object. Every time it runs, it updates all the tagged values on the page. It’s not the most efficient thing to redo everything on the page every time, but it’s a lot simpler, and as I hope I’ve already made clear, this is an imperfect solution for an imperfect codebase.

$  (document).ready(function(){   State.updateState(); });

The first thing the update function does is update the value according to the property it receives. Then it runs the two transformations I mentioned. For text elements, it makes a list of all data-text nodes, grabs their data-tag value, and sets the text to whatever is in the tagged property. Color works a little differently, setting the data-color attribute to the value of the tagged property, and then relies on the CSS, which styles the data-color properties to show the correct style.

I’ve also added a document.ready, so we can run the update function on load and display our default values. You can pull default values from the DOM, or an AJAX call, or just load the State object with them already entered as I’ve done here.

And that’s it! All we do is keep the state in the JavaScript, observe our events, and react to changes as they happen. Simple, right?

What’s the benefit here? Working with a pattern like this maintains a single source of truth in your state object that you control, you can trust and you can enforce. If you ever lose trust that your DOM is correct, all you need to do is re-run the update function with no arguments and your values become consistent with the state object again.

Is this kind of hokey and primitive? Absolutely. Would you want to build an entire system out of this? Certainly not. If you have better tools available to you, you should use them. But if you’re in a highly restrictive legacy codebase like I am, try writing your next feature with Reactive jQuery and see if it makes your code, and your life, simpler.


The post Reactive jQuery for Spaghetti-fied Legacy Codebases (or When You Can’t Have Nice Things) appeared first on CSS-Tricks.

You can support CSS-Tricks by being an MVP Supporter.

CSS-Tricks

, , , , , , ,

How to Make localStorage Reactive in Vue

Reactivity is one of Vue’s greatest features. It is also one of the most mysterious if you don’t know what it’s doing behind the scenes. Like, why does it work with objects and arrays and not with other things, like localStorage?

Let’s answer that that question, and while we’re at it, make Vue reactivity work with localStorage.

If we were to run the following code, we would see that the counter being displayed as a static value and not change like we might expect it to because of the interval changing the value in localStorage.

new Vue({   el: "#counter",   data: () => ({     counter: localStorage.getItem("counter")   }),   computed: {     even() {       return this.counter % 2 == 0;     }   },   template: `<div>     <div>Counter: {{ counter }}</div>     <div>Counter is {{ even ? 'even' : 'odd' }}</div>   </div>` });
// some-other-file.js setInterval(() => {   const counter = localStorage.getItem("counter");   localStorage.setItem("counter", +counter + 1); }, 1000);

While the counter property inside the Vue instance is reactive, it won’t change just because we changed its origin in localStorage

There are multiple solutions for this, the nicest perhaps is using Vuex and keep the store value in sync with localStorage. But what if we need something simple like what we have in this example? We have to take a dive in how Vue’s reactivity system works.

Reactivity in Vue

When Vue initializes a component instance, it observes the data option. This means it walks through all of the properties in data and converts them to getters/setters using Object.defineProperty. By having a custom setter for each property, Vue knows when a property changes, and it can notify the dependents that need to react to the change. How does it know which dependents rely on a property? By tapping into the getters, it can register when a computed property, watcher function, or  render function accesses a data prop.

// core/instance/state.js function initData () {   // ...   observe(data) }
// core/observer/index.js export function observe (value) {   // ...   new Observer(value)   // ... }  export class Observer {   // ...   constructor (value) {     // ...     this.walk(value)   }      walk (obj) {     const keys = Object.keys(obj)     for (let i = 0; i < keys.length; i++) {       defineReactive(obj, keys[i])     }   } }  
 export function defineReactive (obj, key, ...) {   const dep = new Dep()   // ...   Object.defineProperty(obj, key, {     // ...     get() {       // ...       dep.depend()       // ...     },     set(newVal) {       // ...       dep.notify()     }   }) }

So, why isn’t localStorage reactive? Because it’s not an object with properties.

But wait. We can’t define getters and setters with arrays either, yet arrays in Vue are still reactive. That’s because arrays are a special case in Vue. In order to have reactive arrays, Vue overrides array methods behind the scenes and patches them together with Vue’s reactivity system.

Could we do something similar with localStorage?

Overriding localStorage functions

As a first try, we can fix our initial example by overriding localStorage methods to keep track which component instances requested a localStorage item.

// A map between localStorage item keys and a list of Vue instances that depend on it const storeItemSubscribers = {}; 
 const getItem = window.localStorage.getItem; localStorage.getItem = (key, target) => {   console.info("Getting", key); 
   // Collect dependent Vue instance   if (!storeItemSubscribers[key]) storeItemSubscribers[key] = [];   if (target) storeItemSubscribers[key].push(target); 
   // Call the original function    return getItem.call(localStorage, key); }; 
 const setItem = window.localStorage.setItem; localStorage.setItem = (key, value) => {   console.info("Setting", key, value); 
   // Update the value in the dependent Vue instances   if (storeItemSubscribers[key]) {     storeItemSubscribers[key].forEach((dep) => {       if (dep.hasOwnProperty(key)) dep[key] = value;     });   } 
   // Call the original function   setItem.call(localStorage, key, value); };
new Vue({   el: "#counter",   data: function() {     return {       counter: localStorage.getItem("counter", this) // We need to pass 'this' for now     }   },   computed: {     even() {       return this.counter % 2 == 0;     }   },   template: `<div>     <div>Counter: {{ counter }}</div>     <div>Counter is {{ even ? 'even' : 'odd' }}</div>   </div>` });
setInterval(() => {   const counter = localStorage.getItem("counter");   localStorage.setItem("counter", +counter + 1); }, 1000);

In this example, we redefine getItem and setItem in order to collect and and notify the components that depend on localStorage items. In the new getItem, we note which component requests which item, and in setItems, we reach out to all the components that requested the item and rewrite their data prop.

In order to make the code above work, we have to pass on a reference to the component instance to getItem and that changes its function signature. We also can’t use the arrow function anymore because we otherwise wouldn’t have the correct this value.

If we want to do better, we have to dig deeper. For example, how could we keep track of dependents without explicitly passing them on?

How Vue collects dependencies

For inspiration, we can go back to Vue’s reactivity system. We previously saw that a data property’s getter will subscribe the caller to the further changes of the property when the data property is accessed. But how does it know who made the call? When we get a data prop, its getter function doesn’t have any input regarding who the caller was. Getter functions have no inputs. How does it know who to register as a dependent? 

Each data property maintains a list of its dependents that need to react in a Dep class. If we dig deeper in this class, we can see that the dependent itself is already defined in a static target variable whenever it is registered. This target is set by a so-far-mysterious Watcher class. In fact, when a data property changes, these watchers will be actually notified, and they will initiate the re-rendering of the component or the recalculation of a computed property.

But, again, who they are?

When Vue makes the data option observable, it also creates watchers for each computed property function, as well as all the watch functions (which shouldn’t be confused with the Watcher class), and the render function of every component instance. Watchers are like companions for these functions. They mainly do two things:

  1. They evaluate the function when they are created. This triggers the collection of dependencies.
  2. They re-run their function when they are notified that a value they rely on has changed. This will ultimately recalculate a computed property or re-render a whole component.

There is an important step that happens before watchers call the function they are responsible for: they set themselves as target in a static variable in the Dep class. This makes sure the they are registered as dependent when a reactive data property is accessed.

Keeping track of who called localStorage

We can’t exactly do that because we don’t have access to the inner mechanics of Vue. However, we can use the idea from Vue that lets a watcher set the target in a static property before it calls the function it is responsible for. Could we set a reference to the component instance before localStorage gets called?

If we assume that localStorage gets called while setting the data option, then we can hook into beforeCreate and created. These two hooks get triggered before and after initializing the data option, so we can set, then clear, a target variable with a reference to the current component instance (which we have access to in lifecycle hooks). Then, in our custom getters, we can register this target as a dependent.

The final bit we have to do is make these lifecycle hooks part of all our components. We can do that with a global mixin for the whole project.

// A map between localStorage item keys and a list of Vue instances that depend on it const storeItemSubscribers = {};  // The Vue instance that is currently being initialised let target = undefined;  const getItem = window.localStorage.getItem; localStorage.getItem = (key) => {   console.info("Getting", key);    // Collect dependent Vue instance   if (!storeItemSubscribers[key]) storeItemSubscribers[key] = [];   if (target) storeItemSubscribers[key].push(target);    // Call the original function   return getItem.call(localStorage, key); };  const setItem = window.localStorage.setItem; localStorage.setItem = (key, value) => {   console.info("Setting", key, value);    // Update the value in the dependent Vue instances   if (storeItemSubscribers[key]) {     storeItemSubscribers[key].forEach((dep) => {       if (dep.hasOwnProperty(key)) dep[key] = value;     });   }      // Call the original function   setItem.call(localStorage, key, value); };  Vue.mixin({   beforeCreate() {     console.log("beforeCreate", this._uid);     target = this;   },   created() {     console.log("created", this._uid);     target = undefined;   } });

Now, when we run our initial example, we will get a counter that increases the number every second.

new Vue({   el: "#counter",   data: () => ({     counter: localStorage.getItem("counter")   }),   computed: {     even() {       return this.counter % 2 == 0;     }   },   template: `<div class="component">     <div>Counter: {{ counter }}</div>     <div>Counter is {{ even ? 'even' : 'odd' }}</div>   </div>` });
setInterval(() => {   const counter = localStorage.getItem("counter");   localStorage.setItem("counter", +counter + 1); }, 1000);

The end of our thought experiment

While we solved our initial problem, keep in mind that this is mostly a thought experiment. It lacks several features, like handling removed items and unmounted component instances. It also comes with restrictions, like the property name of the component instance requires the same name as the item stored in localStorage. That said, the primary goal is to get a better idea of how Vue reactivity works behind the scenes and get the most out of it, so that’s what I hope you get out of all this.

The post How to Make localStorage Reactive in Vue appeared first on CSS-Tricks.

CSS-Tricks

,
[Top]