Most efficient way of "pushing" data to Polymer elements - javascript

I have a situation in which I get data over a web socket, and performance is important. From the docs I understand that there are various ways of "pushing" the data I'm receiving to my Polymer elements, but I'm curious which one will be most efficient. So far I've created an element that can be included in a template, where the parent element will observe any changes in the data property and react accordingly. I've also been experimenting with using a Behavior to accomplish the same thing, though instead of needing to include a "data-element" in its template, it could just observe its own data property. I realize I could also use something like iron-signals to "push" the data via an event.
I'm not sure any of these methods are very efficient, since most of the time the changes to the "data" object will only apply to a small subset of all the observers. Another possible solution would be to "observe" a dynamic path, so like data.pathx instead of data.*, which would drastically reduce the number of times the observer callback gets fired, but I haven't come across anything that leads me to think that's possible, since each of my elements won't know if it should observe pathx or pathz until creation.
Like I said, performance is vital, and I feel there is way too much inefficiency if I have a small to medium sized dom-repeat of elements each observing a large data object of another element or individually holding a copy of that data on their own (like I assume a behavior would accomplish?).
I've looked at iron-meta, but I haven't been able to successfully data-bind to it, and from what I can tell from the docs, this data needs to be queried, whereas I need to be notified of changes.

Polymer doesn't really "observe" changes in elements. It just sets a setter for each property, and when it's called the UI is updated. So a dom-repeat template will not observe any change inside an object bound to it.
What could impact performance is unnecessary DOM manipulation, so if just a small subset of the data changes, re assigning all the array to the property is not ideal, and you should use notifyPath with just the sub property path and value that changed. Polymer will only update the DOM nodes affected.
If you have a way of knowing what sub properties changed in your data then you could obtain the object paths that have changed and call notifyPath for each of those and only a small number of DOM nodes will be changed.
Additional note:
If the number of elements in your array change, (added/removed) you should use the Polymer base array manipulation methods to update the property of your Polymer element, so it will change the DOM efficiently.

Related

Is this a valid use case for derived state from props? [react]

React documentation seems to be very insistent on the idea that in almost every situation, deriving state from props is a bad idea, an anti-pattern, verbose, likely to cause bugs, hard to understand, and all-around probably going to place a curse on one's lineage for a thousand years.
My use case isn't that weird, so I'm probably doing something wrong, but the suggested patterns for not needing getDerivedStateFromProps() (i.e. making Your object fully controlled or fully uncontrolled) don't seem like good solutions.
The situation: I have a Table component, that takes in an array rows as a prop. Table is used in many different places in my app. I want the Table to be able to handle row-sorting. It is obviously a bad idea to to make whichever parent component controls Table to have to control the sorting*, so fully controlled is out. Making Table fully uncontrolled with a key, also seems like it doesn't make a lot of sense unless the key is the row-data itself-- but my understanding is that key is meant to be simple data (like an id), and actually having to compare all of the rows, which are typically fairly complicated objects, would be pretty inefficient**. Using memoize-one is also not an option as I am working in a closed system and can't import any new libraries.
My current solution: Table has a state variable sortedRows which is updated either whenever sort() is called or whenever props.rows is updated (via getDerivedStateFromProps), by:
Making a shallow copy of props.rows,
in-place sorting that copy and
updating state.sortedRows on that value.
As I see it, there is still only one source of truth here (which is from props), and the state is always just storing a sorted version of that truth (but always dependent on and in sync with it).
Is this solution bad? If so why? What would be a better way to implement this?
Thanks!
Note: I didn't include my code because I am massively simplifying the situation in this prompt-- in reality Table element already exists, and is pretty complicated.
Note 2: I going to ask if I'd run into issues once I want to be able to modify elements in the tables, but I think I'm actually ok, since Table doesn't manage its elements, just arrange and display them, and the buttons for adding and removing elements from a table are not contained within Table, so all that processing is happening at the level of the parent's logic as passed down as part of props.rows
*Having something like <Table rows={sort(rowsFromParent)}/>every time I call Table is repetitive and error-prone, and since clicking on a table header determines sorting column, we'd actually have to have the parent element passing down an onClick() function in every case, which quickly and unnecessarily ramps up complexity).
**There is also a secondary problem to do with rebuilding an element. The table has an infinite scroll, such that when You reach a certain element more rows are loaded in. Using key will destroy the Table component and create a new one, scrolling the user to the top of the new table (which could potentially have many thousands of rows). Something also feels wrong about having to set key in each use of Table, even though resetting based on changes to props.rows seems like it should be intrinsic to how Table works, rather than something that has to be configured each time.
Edit: I have React 15.4, which is before getDerivedStateFromProps was added and using a later version is not an option, so I guess even if I happened to find a valid use case for getDerivedStateFromProps, an alternative would be nice...

How to dynamically access children of a slot

Let's say I have a SearchForm Component that has a Reset button, as well as a slot to include any desired SearchField Components. When I click SearchForm's Reset button, I'd like to call each SearchField's reset method, but I'm having a hard time understanding how to do this dynamically... I obviously don't want to add refs to each SearchField because these aren't static and can change when using the SearchForm in some other part of the application. Fiddle for example.
In Vue2, it seemed liked there was some sort of $children property, but that was taken out in Vue3. I was thinking I could potentially use querySelectorAll to access all "input" elements, but I didn't see how I could access the DOM element's component instance (similar to jQuery's $ selector). If I access the $slots.default() and loop over it, I get some weird object that isn't a component instance... or rather, it doesn't have the typical properties that the component instance has, and I have no clue how to access the actual instance from here.
It's also possible I'm not thinking in a Vue-centric way, as I'm new to the framework, so how can I solve this issue?
I've come up with this solution, but I don't like it, as it adds some minor coupling. Basically, I listen for when the field is created, check its parent, and if it's a form, I push it onto the array of children. Then when the parent's reset is called, it loops through its children. This is a fragile approach because it requires the direct parent to be the form... if the field was nested inside of another component, it won't be added to the form's fields. I'm also pretty sure this breaks the best practices of the framework. It's a shame there doesn't appear to be a way of accessing child instances (without being forced to use ref)... that seems like it'd be desired by a lot of devs.
I came up with yet another way, but once again, seems a little shady because I'm accessing the DOM element's private property __vueParentComponent. I like it better than the previous answer because it's not coupled, and I can use getElementsByTagName. Fiddle for reference. This is the relevant code that I added as a method in SearchForm:
getFields() {
const fields = this.$el.getElementsByTagName("input");
// getElementsByTagName returns an HTMLCollection, which doesn't have map,
// so let's use spread to make an array and use map
return [...fields].map((fieldEl) => {
return fieldEl.__vueParentComponent.proxy;
});
}
Last solution... this one seems to be more stable and the proper Vue way. You use provide/inject; the parent provides the value, and the child injects it, so it can use it. Vuetify does something similar, but they have their own register and unregister methods, which I've created in the Fiddle but as a rudimentary implementation. The only caveat being if you're using TypeScript, the inject won't work properly, and you'll have to use one of these solutions.

Listening for changes in HTMLCollection (or achieving a similar effect)

I need to create a simple tooltip library that works like this:
every DOM element with a specific attribute combination (like class="tooltip", data-tooltip-text="some text") automatically displays a tooltip (containing text from data attr) on hover.
This behavior must persist through external DOM manipulation. I really like the idea of utilizing a HTMLcollection for this, for its "live" nature, as iterating the whole DOM with every DOM change sounds potentially very demanding.
Now I would love to watch/listen the collection and run a sequence every time it changes (iterate through the nodes, see if they have a listener, add it if they don't).
How do I do this? The watch and observe methods seem to (if I understand correctly) be capable of that, but they are now deprecated. MDN says that Proxy covers most use cases, but does it cover mine (I haven't found a way to make it work)? Or is there some other way I'm missing?
And what about MutationObserver? I assume that deep-observing the whole application and repeatedly fetching a new NodeList via querySelectorAll with every single change would be too demanding (the library should run over a React application). Dynamically committing the HTMLCollection (as a value) into DOM via React and then (shallowly) listening for changes with MutationObserver might work, but I doubt that would be a good idea either.

Algorithm to update only the changed innerHTML of the document

I have 2 JS variables. before and after. They contains the SAME html document, but have some modification. About 1%-10% change between them. I want to update the body from before to after. The variablesbefore and after are raw string.
I can do something like that:
document.documentElement.innerHTML=after
The problem is that if I render this way it not look good. The render takes time, and there is a white screen between the renders. I want to show the user 10 modification in a second (video of modifications)
So what I want to do. I want to search and find only the elements that changed only by analyze the HTML text of before and after.
My way of solution:
I can find the changes and the position in the text using Javascript Library for diff & match & patch.
The question is:
After I find the text changes. How to find only the elements who changed. I update only those elements.
I thought, maybe to create a range, that contains every change, and update the range, but how exactly to do that?
If anything unclear, please comment, I will explain better.
I found a very good library for it: https://github.com/patrick-steele-idem/morphdom
Lightweight module for morphing an existing DOM node tree to match a
target DOM node tree. It's fast and works with the real DOM—no virtual
DOM here!
Very easy to use, and doing exactly what I need
If I have understood your question correctly, then what I would have done is,
1) Make a new object (view Object) which will control the rendering of DOM elements. (Similar to MVC)
2) In this object, I would have created 3 functions.
a) init function (contains the event-handlers)
b) render1 function (which will contain elements in before element)
c) render2 function (which will contain elements in after element)
Whenever there is an event where I need to change the HTML of a class/id/body/document, I will change that in init function and call render2 function which contains the after element.
This should not give any error, however the browser has to work to render all the page, but rendering can be divided over multiple elements of document. So, whenever you need to render a part of document, make separate render functions.
p.s. there can be different approaches.
You must implement the LCS(Longest Common Subsequence). To understand better of this algorithm you can watch this youtube video. Also It's easier to first study Longest Common Substring.
I think I have a solution. virtual-dom can do the work for me. I can create two VTree, make a diff, and apply a patch.
From the documentation of virtual-dom:
virtual-dom is what I need.
Manual DOM manipulation is messy and keeping track of the previous DOM
state is hard. A solution to this problem is to write your code as if
you were recreating the entire DOM whenever state changes. Of course,
if you actually recreated the entire DOM every time your application
state changed, your app would be very slow and your input fields would
lose focus.
virtual-dom is a collection of modules designed to provide a
declarative way of representing the DOM for your app. So instead of
updating the DOM when your application state changes, you simply
create a virtual tree or VTree, which looks like the DOM state that
you want. virtual-dom will then figure out how to make the DOM look
like this efficiently without recreating all of the DOM nodes.
virtual-dom allows you to update a view whenever state changes by
creating a full VTree of the view and then patching the DOM
efficiently to look exactly as you described it. This results in
keeping manual DOM manipulation and previous state tracking out of
your application code, promoting clean and maintainable rendering
logic for web applications.
https://github.com/Matt-Esch/virtual-dom

Which way is better? Storing the DOM objects in Array of objects or Direct dom manipulation?

The title may not be too clear but let me explain what I mean by "Which way is better? Storing the DOM objects in Array of objects or Direct dom manipulation?".
I have a list of DOM objects for explanation:
<ul>
<li></li>
...
</ul>
The lis are dynamic and they are updated based on certain operations.
Our requirement is, to check if the list already contains an element with the same text as the new one so for example consider a file listing and you rename a node and if the name already exists, remove all the DOM object which contain the same text and generate the latest one (hope that's pretty much clear).
Now, me and one of my colleague is having a discussion and the discussion is as follows,
My colleague says, store the DOM objects in an array of object and then append them to the list and when the supposedly rename operations is performed, loop through that array of object which stores the reference to the DOM element and do the removing and then generating the new node operation because he believes fetching the element from DOM is gonna be more inefficient.
My idea is, do not store the list and consume the memory as the DOM may get updated at any given point of time so each time you wanna remove and add a node fetch the list do the looping and perform the operations because I believe if you store the list you are consuming the memory and once you update the DOM you'll again have to update the array or else it will store the reference to the old DOM object and that's gonna make it more inefficient.
So please help me understand which method/idea do you think is efficient and why?
Even if you maintain an array of DOM elements, Javascript is still going to have to search the DOM for the elements when you update them. I think the level of complexity you are adding by creating is completely unnecessary. Assuming the custom array method would be more efficient also pretty much assumes that you are going to be able to make this code more efficient than the browsers developers were able to make the Javascript engine in their respective browsers. Probably not a safe bet.
no point of storing data in an array. just use powerful DOM handling framework like jQuery and just work on directly with the DOM.
On rename operation- Loop through the file list for duplicates...if any duplicate is found-prompt the user to choose a different name else go ahead and rename it.
Why would you go for one more array of objects just to loop through when you have the original list unless you want to maintain the original file list array for some other use?
There is no need to maintain an extra array. Most DOM retrieval methods return a NodeList [MDN], which is a live collection of DOM elements, i.e. the collection is always updated when some modification happend.
Thus you can do:
var list_elements = yourlist.getElementsByTagName('li');
and list_elements will always refer to all li descendents of your list.
Update: Of course you can also just keep a reference to yourlist and access the li elements with yourlist.children [MDN].
You can save yourself the extra step and retrieving the elements every time you want to make a modification by keeping a reference to that collection around.
It won't use more memory either (I think) because you just keep a reference to DOM elements (which already exist). When you delete a node, it is removed from the collection automatically, so you don't have to worry about keeping references to "dead" DOM nodes.

Categories