Declarative JS components with viewloader.js
source link: https://www.bensmithett.com/declarative-js-components-with-viewloader-js/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Declarative JS components with viewloader.js
Here's a pattern I've been using lately to attach JS behaviour to a chunk of HTML.
Specify the JS component's name in a data-view
attribute:
Then upon page load (or any other event) call viewloader.execute
with an object containing one-liner setup functions for every component in the app:
Viewloader searches the DOM for every element with a data-view
attribute and calls its setup function.
It's not tied to any particular framework, so you can use it in your app to instantiate any type of component: plain old JS widgets, jQuery plugins, Backbone views. If you really wanted to, you could use it to manually bootstrap an Angular app.
I'm a big fan of writing small, isolated components; lots of little mini-apps that make up the app as a whole. Sometimes you only need a couple of lines of jQuery, sometimes you need a framework to bring a bit more structure. I like being able to mix & match the JS I write within an app while having a consistent method of bootstrapping each new component.
Viewloader itself is a whole 13 lines of code (though it relies on jQuery or Zepto... if you're not using either of those you should be able to tweak it to suit your needs).
PS: Mad props to Toby for introducing me to this idea.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK