Events plugin for jQuery

I developed a free Events plugin for jQuery . Then the plugin was uploaded to GitHub .



The purpose of the plugin is to bind tags to variables.



Subsequently, by setting a new value for the variable, all anchored tags on the page will be updated.



Simple Example



We have tags for displaying data:



<span class='amount'>0</span>
<span class='cart_cost'>0</span>
<span class='order_cost'>0</span>
<span class='order_cost_tax'>0</span>


First, we bind the values ​​of HTML tags and functions to a variable name.



jQuery().event('cost', '.amount');
jQuery().event('cost', '.cart_cost');
jQuery().event('cost', '.order_cost');
jQuery().event('cost', '.order_cost_tax',function(){ return this*1.2});
jQuery().event('cost', function(){ console.log(' :',this)});


Now let's set the value of the variable.



jQuery().var('cost',200); 


With one command, we placed the value 200 in all the tags attached to the cost variable, and we placed the value 240 in the .order_cost_tax tag, which is 20% more than the value of the variable.



Result:



<span class='amount'>200</span>
<span class='cart_cost'>200</span>
<span class='order_cost'>200</span>
<span class='order_cost_tax'>240</span>


By writing this plugin I discovered similar functionality (bind(),on(),trigger())out of the box in jQuery. But after studying, I found out that functions (bind(),on(),trigger())only work with functions. And my plugin is designed mainly for binding to HTML tags and displaying information according to string formatting.



I understood that this plugin will perform React and Angular functions. But it is not so.



The goal of the Events plugin is to be clear, simple for beginners, and perform its functions for those who already have jQuery enabled.



Many developers use jQuery to include all React in addition to just bind variables. But the developer only needs to copy the list of prices to the shopping cart on the site.



This is a plug-in for most companies whose website serves as a form for ordering and selling services. This plugin is intended for landing pages for selling and ordering just a few services, i.e. for simple websites with simple functionality.



For example, a website for companies: a dental office, or a company selling gravestones, furniture or apartment renovation.



The peculiarity of the plugin is that we have:



  • string formatting
  • Snapping objects
  • Bindings are persistent or just one-time per tag or function.
  • String formatting for each individual binding.


I will continue the description.



Now let's set a new value:



jQuery().var('cost',6000); 


Result:



<span class='amount'>6000</span>
<span class='cart_cost'>6000</span>
<span class='order_cost'>6000</span>
<span class='order_cost_tax'>7200</span>


By setting jQuery (). Var ('cost', 6000); we automatically change all the values ​​associated with cost.



Removing the binding to the variable



jQuery().event('cost', false);


// All tags and functions bound to the cost variable will be removed.



Second example



Formatting strings



We create a new binding to the variable:



jQuery().event('cost', '.amount',      '    {0} $');
jQuery().event('cost', '.cart_cost',    ' {0} $');
jQuery().event('cost', '.order_cost',   '{0} $');
jQuery().event('cost', '.order_cost_tax',function(){return '    ${this*1.2} $'});


We bring in



jQuery.var('cost',20);


Result:



<span class='amount'>    20 $</span>
<span class='cart_cost'> 20 $</span>
<span class='order_cost'>20 $</span>
<span class='order_cost_tax'>   24 $</span>


By creating formatting associated with the tag. We no longer think or worry about formats when new values ​​arrive.



Now specifying jQuery (). Var ('cost', 20); new values ​​are automatically displayed in anchored HTML tags.



Removing the binding to the variable



jQuery().event('cost', false);


// All tags and functions bound to the cost variable will be removed.



Third example



Object snapping



jQuery().event('cost', '.amount',      ' {FirstName} {LastName}     {Cost} $.');
jQuery().event('cost', '.cart_cost',    '  {Cost} $    {CountProducts}');
jQuery().event('cost', '.order_cost',   '{FirstName}: {Cost} $');
jQuery().event('cost', '.order_cost_tax',function(){ let averagePrice = this.Cost/this.CountProducts; return ' : ${averagePrice} $   ${averagePrice*1.2} $.'});


Putting the object into the binding



let user = {FirstName:'',LastName:'́',Cost:20,CountProducts:5};
jQuery().var('cost',user);


Result



<span class='amount'>  ́    20  $.</span>
<span class='cart_cost'>  20 $    4</span>
<span class='order_cost'>: 20 $</span>
<span class='order_cost_tax'> : 5 $  6 $  .</span>


By creating formatting in relation to the tag. We no longer think or worry about formats when new values ​​arrive.



Now pointing



jQuery().var('cost',20);


new values ​​are automatically displayed in anchored HTML tags.



Anchor Format



jQuery().event(variableName, SelectorName); 
jQuery().event(variableName, function(e){}); // 
jQuery().event(variableName, false, SelectorName);  //    
jQuery().event(variableName, false, function(e){}); //    
jQuery().event(variableName, SelectorName, FormatString); //      
jQuery().event(variableName, SelectorName, function(e){}); //        
jQuery().event(variableName, SelectorName, false); //   
jQuery().event(variableName, bindName, SelectorName);//       
jQuery().event(variableName, bindName, function(e){}); //   ,   
jQuery().event(variableName, bindName, false); //     
jQuery().event(variableName, false); //      


Variable Format



let name=jQuery().var(variableName); //   
jQuery().var(variableName,variableValue); //   
jQuery().var(variableName,variableObject); //   
jQuery().var(variableName,null); //  




Event function format:



function(e){
    e.unbind(); // .
    e.id; // 
    e.elements; //jQuery 
    e.value; //     .
    this; //     .
    return false; //    .
    return " {0}  !"; //      HTML 
    return '   HTML '; //      HTML 
}


String format



{this} - ;

{0} - ;

{value} - ;

{FirstProp} -

{SecondProp} -

{ThirdProp} -

1: " {0} !"

2: " {FirstProp} {SecondProp} "




Plugin alias (Function short form)




    jQuery.e(); //  jQuery().event()
    jQuery.v(); //  jQuery().var()
//:
    $.e('cost','.cost'); //    Event
    $.v('cost',100); //    Var


Epilogue



Many will say that jQuery has already outlived its usefulness and does not meet the needs of the market, and therefore it makes no sense to write a plugin for it.



And I will answer that because it does not satisfy, that it did not have simple functions that everyone needs.



Now I will hope that the world will become a little better. And I hope that now something interesting has come to light.



Do you think you would personally find the plugin useful in one of your projects? Any comments would be welcome.



Your Sergey.



PS Commentatorfridaynoticed that this library does not know how to bind Lists by pattern, as `backbone` can do with` marionette`.

This is not the case, here is a very simple example in the previous version:



Binding an array of objects




jQuery().event('listUsers','.listUser',function(){ 
    let html = '';
    for(let user of this){
        html += "<div> <span>${user.FirsName}</span>  <span>${user.LastName}</span> :  ${user.Amount} ₽ </div>";
    }
    return html;
});

let users = [
    {FirsName:'',LastName:'',Amount:'5000000' },
    {FirsName:'',LastName:'',Amount:'1000000' },
    {FirsName:'',LastName:'',Amount:'5000000' },
];

jQuery().var('listUsers',users,'');
//3-  ''( )   var()   /       .  




Addition of the article, modification of the plugin to expand the possibilities



Thanks to fair criticism from the commentators below. I have modified and added new features:

  1. Dynamic array binding
  2. Dynamically snapping an object
  3. Loading and unloading all bindings into a plugin in one collection.
  4. The formatting of the object data string is almost done .




Dynamic array binding



This allows you to add an element or properties of a bound array or object dynamically by adding (modifying, removing) a child tag.

Example:


<div class='people'></div>
We bind:


jQuery().event('users', '.people');
Create an object and apply


var usersList =[
    ' ',
    ' ',
    ' ',
    .........
];
jQuery().var('users', usersList);


As a result, we get:


<div class='people'>
    <div> </div>
    <div> </div>
    <div> </div>
</div>


And also we can now add (change, delete) dynamically list items.


jQuery().var('users', ' ', true);//    


Result:


<div class='people'>
    <div> </div>
    <div> </div>
    <div> </div>
         <div> </div>
</div>


A new position has been added to the list.

Now we will delete and change one of the existing positions referring only to the bound array.


jQuery().var('users', ' ', false);//   
jQuery().var('users', ' ', 1);//      1
jQuery().var('users', null, 3);//      3
jQuery().var('users', ' ', true);//    
jQuery().var('users', ' ', 5);//       5


1.We removed the tag from the 'Madonna Chicone' in the list by removing the array element with that name.

2. We changed the contents of the tag with index 1 in the array to 'Angelina Jolie'.

3. We removed the tag with the content by removing the position in the array at index

4. Added a new tag with the content 'Jennifer Lopez' to the end of the list.

5.Added a new tag with the content 'Jennifer Lawrence' by adding it to the array at index 5.



Dynamically snapping an object




<div class='person'></div>



jQuery().event('user', '.person');//   HTML
var userData ={
    FirstName:'',
    LastName:'',
    salary: 200000,
};
jQuery().var('user', userData);//   HTML


Result:


<div class='person'>
    <div></div>
    <div></div>
    <div>200000</div> 
</div>


We change the values ​​of the object bound to HTML by analogy with an array:


jQuery().var('user', null,'FirstName');//   
jQuery().var('user', '','FirstName');//    
jQuery().var('user', 500000,'salary');//     .
//            .
//        .
// ,   3-   ,    .




The format of the 3rd parameter of the VAR () method:




jQuery().var('users', , '');//3  ('')  .  /   /
jQuery().var('users', , null);//3  (null).  /      /,   .
jQuery().var('users', , undefined);//3  (undefined).   /   : 
//           /-   ,    jQuery().var('users', , null)  
//         /-   ,    jQuery().var('users', , '')  
//    ,     /-.
jQuery().var('users', C, false);//          /
jQuery().var('users', C, true);//        /.
jQuery().var('users', C, 3);//      3  /.
jQuery().var('users', null, 3);//      3
jQuery().var('users', C, ' ');//      /.
jQuery().var('users', null, ' ');//     /.
jQuery().var('users', C, {property:' ',...  .});//     //          ,           , , ,  .




Advanced functionality / Format of the 3rd parameter as an object for the VAR () method




let setting = {
    tagListItem: 'li', //    ,   DIV
    classListItem:'classTagChildren', //    
    onlyone: true, //      .
    format: '{this}',//         
    anyData: {data1:'  '},//        .
};
// setting     ,        .
jQuery().event('user', '.person',setting);//      .
jQuery().var('user', user, setting);//       .




Loading / unloading bindings




let events = {};
events['user']['.person'] = function(value,data){ return ' {value.name},   '+(0.8*value.salary)};
events['user']['.status'] = '  {value},   {salary}';
jQuery().event(events);//    

let eventsUser = {};
eventsUser['.person'] = function(value,data){ return ' {value.name},   '+(0.8*value.salary)};
eventsUser['.status'] = '  {value},   {salary}';
jQuery().event('user', eventsUser);//        users.
//'user' -   /      $.event() 
//'.status', '.person' -   /      $.event() 

jQuery().event();//    .

jQuery().var();//    .
jQuery().var([...]);//    .




New plan



  1. Refine string formatting
  2. Adding reactivity: Bindings to INPUT, SELECT and others controls to update the feedback in bound variables.


PS



Hopefully now jQuery believers will not accept faith in Vue, Angular, React and others. The world will be fair and diverse and everyone will have their own side.



All Articles