JS templating engine that preserves elements - javascript

I have the following problem:
A have a web application where I regularly need to update the user interface when data changes. The data consists of a list of items with different attributes. Because the UI representations of these items can be complex, I use JS templating to render them. When they change I just replace them in the DOM with the HTML representing their updated state.
This approach is simple but has several problems:
you need to re-attach all event handlers because you practically replace elements
there is a flickering effect when reloading resources (probably can be solved using document fragments)
it's impossible to work with developer tools (inspector) if the content changes frequently because, again, all the elements are replaced
So I was wondering if there is any JS templating engine of that many that can deal with the situation. I'm thinking of a feature that intelligently matches elements of the new render and an old one and only changes the content when it has really changed.
I'm thinking of something like this:
Old HTML
<div>
<h1>TV</h1>
<span>$250</span>
Add to cart
</div>
New HTML
<div>
<h1>TV</h1>
<span>$260</span>
Add to cart
</div>
The templating engine find the <span> in the original DOM and replaces its changed value but leaves the rest of the elements intact.

Finally I came across Rivets.js which a lightweight, highly extensible JavaScript templating engine with real time data binding. I love it so far, it's exactly what I needed.

you can try the AngularJS
A simple example:http://jsbin.com/opayuf/4/edit
you can check out these examples if they can meet your requirements
http://tutorialzine.com/2013/08/learn-angularjs-5-examples/
HandleBarsJs may be the one you need, you could see the discussion on
Handlebars.js: Use a partial like it was a normal, full template
You can also try Ember js based on HandlerBarsJs, you can check is out
http://emberjs.com/guides/templates/handlebars-basics/
http://emberjs.com/guides/templates/rendering-with-helpers/

Related

How to re-render hyperHTML to the same element after content change

I am trying to support the same type of thing as React.Children
My code looks like
const elem = document.getElementById("profile")
const render = hyperHTML.bind(elem);
const name = elem.textContent
render`<b>Hi ${name}</b>`
So the API looks like
<div id="profile">alax</div> 🢂 <div id="profile"><b>Hi alax</b></div>
and I am using MutationObserver to rerender on content change
But if the content is changed. hyperHTML says its rending to the right element.. but the element keeps its innerHtml(No update)
I can see the <!--_hyper: -2001947635;--> is removed then the content is set but setting up the render & hyperHTML.bind again does nothing
Any thoughts would be great! Thx
Update
The fix to the above problem is to call hyperHTML.bind`` then your normal render using hyperHTML will work
Context -
I am using hyperHTML to create a custom element library(hyper-element)
My use case: I work in a mix-tech project (some people use jQuery)
Side note, on the why. I want to support something like partial templates
Example of a partial template:
<user-list data="[{name:'ann',url:''},{name:'bob',url:''}]">
<div>{#name}</div>
</user-list>
Output:
<user-list data="[{name:'ann',url:''},{name:'bob',url:''}]">
<div>ann</div>
<div>bob</div>
</user-list>
This is one use of setting custom content in an element you control
At the moment I have the setting of the content by 3-party working/re-rending
https://jsfiddle.net/k25e6ufv/16/
My problem is now: it is rending another custom element and getting the pass content to child element
It looks like hyperHTML is setting the child element's content in front to the element and creating the element without setting the content
Scroll down to bottom of source to see implementation!
https://jsfiddle.net/k25e6ufv/14/
Rending crazy-cats:
Html`
xxx: ${this.wrapedContent} zzzz
`
Current output:
wrapedContent: ppp time:11:35:48 ~ crazy-cats: **Party 11:35:48** xxx: zzzz
<crazy-cats>Party 11:37:21 xxx: <!--_hyper: -362006176;--> zzzz </crazy-cats>
Desired output:
wrapedContent: ppp time:11:35:48 ~ crazy-cats: xxx: **Party 11:35:48** zzzz
<crazy-cats> xxx: Party 11:37:21 zzzz </crazy-cats>
I will try to answer as best as I can, but I'll start saying that when asking for help, it'd be much easier/better to show the simplest use case you are trying to solve.
There is a lot of "surrounding" code in your fiddles so that I'll try to answer only to hyperHTML related bits.
hyper-element ?
I am not sure what's the goal of the library but hyperHTML exposes hyper.Component, and there's also an official HyperHTMLElement class to extend, which does most of the things you manually implement in your examples.
I'll keep answering your questions but please consider trying, at least, the official alternative and maybe push some change there if needed.
partial templates
hyperHTML pattern and strength is the Template Literal standard. Accordingly, to generate TL from the DOM would require either parsing of the content or code evaluation. Both solutions aren't the way to go.
Custom Elements require JavaScript to work, and without JS your partial template is useless and also potentially confusing for the user/consumer.
You don't want to define what to do with the data in the layout, you want to define a Custom Element behavior within the class that defines it.
That means: get rid of old-style in-DOM output, and simply use the Custom Element class to define its content. You maintain the related class only instead of maintaining a layout that has no knowledge about how the CE should represent that data.
TL;DR the following is a bad hyperHTML pattern:
<user-list data="[{name:'ann',url:''},{name:'bob',url:''}]">
<div>{#name}</div>
</user-list>
all you want to do is to write this:
<user-list data="[{name:'ann',url:''},{name:'bob',url:''}]"></user-list>
but be careful, the data attribute in hyperHTML is special only if passed through the template literal. If you want to pass JSON to the component, call the attribute differently.
// hyperHTML data is special, no need to use JSON
render`<c-e data=${{as: 'it is'}}></c-e>`
Above snippet is different from having JSON as data attribute text so your example should use data-json name, and the class should remember to JSON.parse(this.dataset.json) in its constructor (or have an attribute observer that does that for you)
hyperHTML owns elements
When you write:
it looks like hyperHTML is setting the child element's content in front to the element and creating the element without setting the content
you are assuming you should care at all what hyperHTML does: you shouldn't.
The only thing you should understand is that hyperHTML owns the node it handles. If you trash those nodes via different libraries or manually, you are doing something wrong.
hyperHTML(document.body)`<p>hello ${'world'}</p>`;
// obtrusive libraries ... later on ...
document.body.textContent = 'bye bye';
// hyperHTML still owns the body content
hyperHTML(document.body)`<p>hello ${'world'}</p>`;
Above snippet is perfectly fine and totally wrong at the same time.
You don't update the body content manually, you don't interfere with its content via jQuery or other libraries, and you should never trash the content at all.
Once you chose hyperHTML to handle a bound context, that's it, you've made your choice.
This is true for pretty much every library on this world. If you use Angular to create something and you mess it all via jQuery, that breaks. If you write backbone templates and you mess later on with their content manually, that breaks.
If you bind an element to hyperHTML and you mess it up with other libraries, that breaks.
The only thing that won't break are wires, meaning the moment you create a wire, you can append it directly and that's actually a DOM node so it will be there, and it will be handled by hyperHTML.
Yet you should use hyperHTML to handle those changes, never jQuery or JS itself.
The output is right
When you say that the output should not contain the comment you are assuming you should care what output is produced via hyperHTML: you shouldn't!
hyperHTML uses comments as delimiters and these are absolutely fine for both performance, being unaffected by repaint and reflows, and for partial changes like the following one:
hyperHTML(document.body)`<p>${'a'} b ${'c'}</p>`
Both a and c will have a comment as anchor node to be able to update their content with anything later on.
hyperHTML(document.body)`<p>${[list, of, nodes]} b ${otherThing}</p>`
You change interpolations? All good, hyperHTML knows what to replace and where.
force-own the content
If you use a different template literal to re-populate a bound node you are trashing the cache and creating new content.
At that point you are better off with innerHTML because all the features of hyperHTML will be gone.
To start with, if your content can change so much, use an array.
hyper(document.body)`${['text']}`;
// you can clean up the text through empty array
hyper(document.body)`${[]}`;
// re-populate it with new content
hyper(document.body)`${['a', 'b', 'c']}`;
Above example is still better than changing template because all the optimizations for the content will be already there.
However, if you want to be sure the node the initial one created via hyperHTML, assuming no third parts script mutate/trash that node, you can use a wire.
const body = hyper()`<p>my ${'content'}</p>`;
document.body.textContent = '';
document.body.appendChild(body);
It's a bit extreme but at least faster.
As Summary
It looks like you are trying to sneak in hyperHTML into an application that trashes layout all the time through different third parts libraries.
Unless you create a closed Shadow DOM reference and you drop partial template through layout, you'll always have issues with libraries based on side effects with DOM content, libraries that mutates elements they don't own.
In hyperHTML the ownership concept is key, like in React you cannot change at runtime the defined JSX for the component, you should never try to change at runtime the defined template literal for hyperHTML.
Now, as much as I'd like to solve all your issues, I feel like it's right to ask you: are you sure hyperHTML is really the solution for your current app? It looks like surrounding side-effects caused by third parts libraries would constantly break your expectations if you don't use closed mode Shadow DOM and hyperHTML only to update your DOM.

Shared custom element creation performance

The Polymer documentation suggests using a custom element for sharing some static data, like configuration. Something like <app-settings>.
I'm wondering whether it is optimal from performance point of view. Whenever such non-visual element is used it has to be created nonetheless. Wouldn't it be better to simply share the settings in a global variable or in a form of a (AMD/requirejs) module?
The same goes for purely functional tags like <iron-ajax>. If I place many of the inside my custom elements wouldn't it affect performance as opposed to simply using some existing XHR library?
No it's not optimal from a performance point of view.
Custom Elements are slowly created (and is even slower with polyfill).
I think a non-visual object gains nothing to be a Custom Element.
You're right, a simple object would do the job better. Don't get polymerized :-)
http://jsperf.com/new-vs-create-element/3

Bind javascript events to MVC controls

What is the best way to bind Javascript events to my custom MVC controls? My initial thought is to create the controls using Html Helpers which give them a CSS class that signifies what kind of control they are. Then, on document.ready, I'll use jQuery to select all such controls by their class name and bind their events.
However, I'm concerned about the speed of selecting from the entire dom by class name. I've read (and experienced) how slow this can be, especially in IE8 which we need to target for this project.
I could select by IDs by creating a js file for each page, but I'd rather not do this, as it's a complicated web app with lots of pages. I'd rather have one js file for each type of control that gets included in a view if the view contains at least one of that type of control.
Are CSS classes my best option? Any other ideas? I'm using MVC3.
My advice would be to try it out with classes and test the performance. If you are not satisfied, switch to IDs. I use class selectors all the time and don't find them terribly slow in any browser. When you give jquery a context to search in, things are quite fast. For example:
$('#controls .control').whatever();
Or
$('.control', '#controls').whatever();
Sizzle is great at optimizing these things to be fast.
Edit: Here is a good reference for jQuery performance tips in general (notice #5):
http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/

HTML: Fastest/Best way to update contents of many cells in a large table (jQuery or JavaScript)

All,
I'm working on an HTML page that includes a large data table.
As the user interacts with a variety of controls on that page, I'd like the data in the table to update, without reloading the page.
In other words, when the user changes the value of a control, that triggers a JavaScript function that performs a number of calculations, then "updates" the data in the table. In a typical scenario, anywhere from 50 to 500 cells would require updating.
My baseline approach:
assign each <td> cell a unique ID
in the JavaScript function, use document.getElementById() to get a reference to each cell that needs updating
use innerHTML to update those cells
This works fine, but it's probably very slow. E.g., does each call to innerHTML force the browser to re-render the entire table? In other words - does updating 500 cells trigger 500 're-renders'? Or, does the browser only re-render the table once the function is complete?
Long story short, what's the best way to do this?
My current approach?
recreate the entire table as a string in JavaScript, then use ONE call to innerHTML on the div that contains the table?
something else?
I recently watched Paul Irish's EXCELLENT (imo) presentation about optimizing JavaScript performance:
DOM, HTML5, & CSS3 Performance
In that, he describes making changes "off DOM"; unfortunately - that's mostly over my head, and his presentation doesn't include any actual code examples.
I'd prefer a straight JavaScript solution, but I'd be happy with a jQuery solution as well.
Many thanks in advance for any advice or insight.
I think using innerHTML is the way to go.
If each cell has it's own ID then the browser does not need to refresh the whole table to update a single cell.
I am using innerHTML in my current website that I am building and it works very quickly.
As long as you assign the function to the correct action that should work well.
If multiple cells will have the same value, then consider using classes,
in which case jQuery does make it easier to reference classes.
So basically, use your current approach.
Just re rendering each cell when needed is the quickest way (from my understanding and logic)
The approach you are taking is OK. However, it would be advisable to use jQuery or another abstraction library, which will take care of any quirks in the implementation of innerHtml in various browsers (some browsers are case sensitive etc.); this will make your life easier, and leave you to concentrate on developing your logic rather than working on browser idiosyncracies.
this question might be argumentative ... but I would suggest using something like jQuery jGrid plugin
it seems to me might be better that way

Is there a way to create your own HTML element?

Is there a way to create your own HTML element? I want to make a specially designed check box.
I imagine such a thing would be done in JavaScript. Something akin to document.createHTMLElement but the ability to design your own element (and tag).
No, there isn't.
The HTML elements are limited to what the browser will handle. That is to say, if you created a custom firefox plugin, and then had it handle your special tag, then you "could" do it, for varying interpretations of "doing it". A list of all elements for a particular version of HTML may be found here: http://www.w3.org/TR/html4/index/elements.html
Probably, however, you don't actually want to. If you want to "combine" several existing elements in such a way as they operate together, then you can do that very JavaScript. For example, if you'd like a checkbox to, when clicked, show a dropdown list somewhere, populated with various things, you may do that.
Perhaps you may like to elaborate on what you actually want to achieve, and we can help further.
Yes, you can create your own tags. You have to create a Schema and import it on your page, and write a JavaScript layer to convert your new tags into existing HTML tags.
An example is fbml (Facebook Markup Language), which includes a schema and a JavaScript layer that Facebook wrote. See this: Open Graph protocol.
Using it you can make a like button really easily:
<fb:like href="http://developers.facebook.com/" width="450" height="80"/>
The easiest way would be probably to write a plugin say in Jquery (or Dojo, MooTools, pick one).
In case of jQuery you can find some plugins here http://plugins.jquery.com/ and use them as a sample.
You need to write own doctype or/and use own namespace to do this.
http://msdn.microsoft.com/en-us/magazine/cc301515.aspx
No, there is not. Moreover it is not allowed in HTML5.
Take a look at Ample SDK JavaScript GUI library that enables any custom elements or event namespaces client-side (this way XUL for example was implemented there) without interferring with the rules of HTML5.
Take a look into for example how XUL scale element implemented: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/elements/scale.js and its default stylesheet: http://github.com/clientside/amplesdk/blob/master/ample/languages/xul/themes/default/input.css
It's a valid question, but I think the name of the game from the UI side is progressive markup. Build out valid w3 compliant tags and then style them appropriately with javascript (in my case Jquery or Dojo) and CSS. A well-written block of CSS can be reused over and over (my favorite case is Jquery UI with themeroller) and style nearly any element on the page with just a one or two-word addition to the class declaration.
Here's some good Jquery/Javascript/CSS solutions that are relatively simple:
http://www.filamentgroup.com/examples/customInput/
http://aaronweyenberg.com/90/pretty-checkboxes-with-jquery
http://www.protofunc.com/scripts/jquery/checkbox-radiobutton/
Here's the spec for the upcoming (and promising) JqueryUI update for form elements:http://wiki.jqueryui.com/Checkbox
If you needed to validate input, this is an easy way to get inline validation with a single class or id tag: http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
Ok, so my solution isn't a 10 character, one line solution. However, Jquery Code aside, each individual tag wouldn't be much more than:
<input type="checkbox" id="theid">
So, while there would be a medium chunk of Jquery code, the individual elements would be very small, which is important if you're repeating it 250 times (programmatically) as my last project required. It's easy to code, degrades well, validates well, and because progressive markup would be on the user's end, have virtually no cost on the server end.
My current project is in Symfony--not my choice--which uses complex, bulky server-side tags to render form elements, validate, do javascript onclick, style, etc. This seems like what you were asking for at first....and let me tell you, it's CLUNKY. One tag to call a link can be 10 lines of code long! After being forced to do it, I'm not a fan.
Hm. The first thought is that you could create your own element and do a transformation with XSLT to the valid HTML then.
With the emergence of the emerging W3 Web Components standard, specifically the Custom Elements spec, you can now create your own custom HTML elements and register them with the parser with the document.register() DOM method.
X-Tag is a helpful sugar library, developed by Mozilla, that makes it even easier to work with Web Components, have a look: X-Tags.org

Categories