Practicing Modular JavaScript - Object Literal Pattern
credits to the owner.
A Pen by Jeferson York B. Mari on CodePen.
| <div class="basket"> | |
| <h1>Fruits</h1> | |
| <input type="text" placeholder="Enter Fruit"/> | |
| <button class="addFruit">ADD</button> | |
| <ul class="fruit-list"> | |
| <script class="fruit" type="text/template"> | |
| {{#fruit}} | |
| <li> | |
| <span>{{.}}</span> | |
| <i class="delete">×</i> | |
| </li> | |
| {{/fruit}} | |
| </script> | |
| </ul> | |
| </div> |
Practicing Modular JavaScript - Object Literal Pattern
credits to the owner.
A Pen by Jeferson York B. Mari on CodePen.
| //Import JQuery.js | |
| //Import Mustache.js | |
| (function() { | |
| var fruit = { | |
| fruit_name: ['Apple', 'Mango', 'Banana'], | |
| init: function() { //init output | |
| this.cacheDOM(); | |
| this.bindEvents(); | |
| this.render(); | |
| }, | |
| cacheDOM: function() { //Cache Dom | |
| this.$basket = $('.basket'); | |
| this.$input = this.$basket.find('input'); | |
| this.$btn = this.$basket.find('button'); | |
| this.$list = this.$basket.find('.fruit-list'); | |
| this.fruit_list = this.$basket.find('.fruit').html(); | |
| }, | |
| bindEvents: function() { //Bind | |
| this.$btn.on('click', this.addFruit.bind(this)); | |
| this.$list.on('click', 'i.delete', this.deleteFruit.bind(this)); | |
| }, | |
| render: function() { //render | |
| var data = { | |
| fruit: this.fruit_name, | |
| }; | |
| this.$list.html(Mustache.render(this.fruit_list, data)); | |
| }, | |
| addFruit: function() { | |
| this.fruit_name.push(this.$input.val()); //push data to the array | |
| this.render(); //render method | |
| this.$input.val(''); //empty input after push the data | |
| }, | |
| deleteFruit: function(event) { | |
| var $del = $(event.target).closest('li'); //when click the i, it will find the closest li | |
| var x = this.$list.find('li').index($del); //find the index of the clicked li | |
| this.fruit_name.splice(x, 1); //splice or removed out | |
| this.render(); | |
| } | |
| } | |
| fruit.init(); //run init | |
| })() | |
| /*var Fruit = { | |
| name : "Apple", | |
| color: "Red", | |
| alertName : function(){ | |
| alert(this.name); | |
| }, | |
| changeName : function(newName){ | |
| this.name = newName;//SetNewName | |
| } | |
| } | |
| Fruit.changeName('StrawBerry'); | |
| Fruit.alertName();*/ |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script> | |
| <script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.1.3/mustache.min.js"></script> |