📜 ⬆️ ⬇️

jQuery plugin for organizing components on the page

JBlocks is a small jQuery plugin (~ 100 lines) for organizing components on a page.

Based on three basic principles:


If you are interested in the topic of declarative javascript - I ask for cat.

Suppose we have a simple control: a counter. Counter step is a parameter that can be changed for different instances.
image
Demo
')
Let's declare a new component counter :

$.jblocks({ //   name: 'counter', //   events: { //  : b-inited, b-destroyed 'b-inited': 'oninit', // - 'click .js-inc': 'onClickPlus', 'click .js-dec': 'onClickMinus' }, //   methods: { oninit: function() { this.$info = this.$node.find('.js-info'); this.count = 0; }, /** *     */ onClickPlus: function() { this.inc(); this.update(); }, /** *     */ onClickMinus: function() { this.dec(); this.update(); }, /** *   */ inc: function() { this.count += this.params.step; }, /** *   */ dec: function() { this.count -= this.params.step; }, /** *    */ update: function() { this.$info.text(this.count); } } }); 

Mark in html component using special attributes:

 <div class="foo" data-b="ounter" data-p='{ "step": 2 }'> ... </div> 



Components can be initialized using $ .fn.jblocks ('init') and destroyed using $ .fn.jblocks ('destroy') :

 //      $(document).jblocks('init'); //      $(document).jblocks('destroy'); //     DOM- $('#app').jblocks('init'); 

Using the $ .fn.jblocks ('get') function, you can get references to instances. If the component has not yet been initialized, it will be done first.

 $('.foo').jblocks('get').each(function() { // this -  , inc —   this.inc(); }); 


UPD:

Thanks to everyone for their constructive criticism (and even one pool request). Updated the repository and article description in accordance with the new API.

UPD:

As GIum correctly noted, this is not “nano” as long as it depends on jQuery. Now it’s really a few hundred lines of vanillajs :)

Source: https://habr.com/ru/post/268109/


All Articles