简体   繁体   中英

Call an object method from html in javascript

I wrote a class for simple booking system. Data is kept in an array and all the edit and delete operations are performed to this array using functions inside that class. So placed buttons to perform edit and delete. How can I call a method from my class to the onclick event of a button. Please check the following code.

Class file

/**
 * Class for handling general insert, update, delete 
 * oprations for a room booking system.
 */
var bookingSystem = function (){
    this.editMode = false; 
    this.editIndex = false;

    // option data for Number of  persons drop down
    this.numPersonsOpts = [
        {name : 1, val : 1},
        {name : 2, val : 2},
        {name : 3, val : 3},
        {name : 4, val : 4}
    ];

    // Sample data to show initially
    this.bookingData = [
        {name : "John", roomType : "AC", numPersons : 3},
        {name : "Mishal", roomType : "Non AC", numPersons : 1}
    ];

    var self = this; // get a reference to this. 

    /**
     * Prepare and show options for dropdown
     * @param string selectorId id of the dropdown
     * @param object optionData array object contains name and value for the options 
     */
    this.showOptions = function (selectorId, optionData){
        var optsStr = "";
        for (var i=0; i<optionData.length; i++) {
            optsStr += '<option value='+optionData[i].val+'>'+optionData[i].name+'</option>';
        };
        document.getElementById(selectorId).innerHTML = optsStr;
    }

    /**
     * To save and update data
     */
    this.saveBooking = function (){
        var name = document.getElementById("bookingName").value;
        if(name){
            var singleEntry = {
                name : name,
                roomType : document.querySelector('input[name="roomType"]:checked').value == 1? 'AC' : 'Non AC',
                numPersons : document.getElementById("numPersonSelect").value
            }
            if(self.editMode){
                if(typeof(self.editIndex) == 'number'){
                    self.bookingData[self.editIndex] = singleEntry;
                    self.editIndex = false;
                }
                self.editMode = false;
            }else{
                self.bookingData.push(singleEntry);
            }

            document.getElementById("bookingName").value = '';
            self.renderTemplate();
        }   
    }
    /**
     * To edit a particular item
     * @param number index array index to edit
     */
    self.edit = function (index){
        self.editIndex = index;
        self.editMode = true;

        document.getElementById("bookingName").value = self.bookingData[self.editIndex].name;
        document.querySelector('input[name="roomType"][value="1"]').checked = self.bookingData[self.editIndex].roomType == 'AC'? true: false;
        document.querySelector('input[name="roomType"][value="2"]').checked = self.bookingData[self.editIndex].roomType == 'Non AC'? true: false;
        for(var i=0; i<this.numPersonsOpts.length; i++){
            document.getElementById("numPersonSelect").options[i].selected = false;
        }
        document.getElementById("numPersonSelect").options[(self.bookingData[self.editIndex].numPersons)-1].selected = true;
    }

    /**
     * To delete a particular item
     * @param number index array index to delete
     */
    self.deleteItem = function (index){
        self.bookingData.splice(index,1);
        self.renderTemplate();
    }

    /**
     * To preapre table content and show it.
     */
    this.renderTemplate = function (){
        var template = '';  
        if(self.bookingData.length > 0){
            for(var i= 0; i< self.bookingData.length; i++){
                template += '<tr>';
                template += '<td>'+self.bookingData[i].name+'</td>';
                template += '<td>'+self.bookingData[i].roomType+'</td>';
                template += '<td>'+self.bookingData[i].numPersons+'</td>';
                template += '<td><button type="button" onclick = "edit('+i+')">Edit</button></td>';
                template += '<td><button type="button" onclick = "deleteItem('+i+')">Delete</button></td>';
                template += '</tr>';
            }
        }else{
            template += '<tr>';
            template += '<td colspan="2"> No Data Found.</td>';
            template += '</tr>';
        }
        document.getElementById("renderTable").innerHTML = template;
    }


}

General code for initializing it.

var bs = new bookingSystem(); // Create object for bookingSystem
var init= function(){
    bs.showOptions('numPersonSelect',bs.numPersonsOpts); // Show number of persons option

    // Save Button event
    var btn = document.getElementById("saveBookingBtn");
    if(btn.addEventListener){
        btn.addEventListener('click',bs.saveBooking);
    }else{
        btn.attachEvent('onclick',bs.saveBooking);
    }

    bs.renderTemplate();
}
function edit(index){
    bs.edit(index); 
}
function deleteItem(index){
    bs.deleteItem(index);   
}

init() is called from body onload event. Following is the html code.

<body onload="init()">
    <form>
        <div class="formRow">
            <label>Name : </label>
            <input type="text" id="bookingName" name="bookingName" value=""> 
        </div>
        <div class="formRow">
            <label>AC/NO : </label>
            <input type="radio" value="1" name="roomType" checked="checked"> AC 
            <input type="radio" value="2" name="roomType"> Non AC 
        </div>
        <div class="formRow">
            <label>Number of Persons</label>
            <select name="numPerson" id="numPersonSelect">

            </select>
        </div>
        <div>
            <button type="button" id="saveBookingBtn">Save</button>
        </div>
    </form>
 <div id="renderArea"></div>
 <table>
    <td>Name</td>
    <td>Room Type</td>
    <td>Person(s)</td>
    <td>Edit</td>
    <td>Delete</td>
    <tbody id="renderTable"></tbody>
 </table>
</body>

This code is working fine. But here I created edit and deleteItem methods to call the actual edit and delete methods wrote in the class. How to use that methods from class directly to onclick event. Like this <button onclick="bs.edit()">Edit</button>

 $(function(){ var productManagement = function() { var products = [ {id:1, name: 'samsung galaxy', price: 6000, description: 'samsung galaxy mobile phone'}, {id:2, name: 'apple', price: 10000, description: 'apple mobile phone'}, {id:3, name: 'nokia', price: 5000, description: 'nokia mobile phone'}, {id:4, name: 'motorola', price: 7000, description: 'motorola mobile phone'} ]; var selectedProducts = {}; var $this = this; this.displayProducts = function() { $.each(products, function(k, product){ $('.content').append($this.getProductInfo(product)); }); } this.getProductInfo = function(product) { var html = '<div class="item" id="' + product.id + '">'; html += '<table><tr><td>Name</td><td>:&nbsp;' + product.name + '</td></tr>'; html += '<tr><td>Price</td><td>:&nbsp;' + product.price + '</td></tr>'; html += '<tr><td>Description</td><td>:&nbsp;' + product.description + '</td></tr>'; html += '<tr><td colspan="2"><button class="addToCart">Add To Cart</td></tr></table>' html += '</div>'; return html; } this.delegate = function() { $('body').delegate('.addToCart', 'click', function(){ var id = $(this).closest('div').attr('id'); if( selectedProducts[id] == undefined) { selectedProducts[id] = 1; }else{ selectedProducts[id]++; } // selectedProducts.push(id); $('.content').hide(); $('.cart').show(); $this.showCart(); }); $('body').delegate('#continueShopping', 'click', function(){ $('.content').show(); $('.cart').hide(); }); $('body').delegate('.remove', 'click', function(){ var id = $(this).closest('tr').attr('id'); $this.removeFromSelected(id); }); } this.removeFromSelected = function(productId){ $.each(selectedProducts, function(pid, numberOfItems){ if( pid == productId) { delete selectedProducts[pid]; return false; } }); $this.showCart(); } this.showCart = function() { var html = '<table><tr><th>Name</th><th>Unit Price</th><th>No of Items</th><th>Total Price</th><th>Action</th></tr>'; var total = 0; $.each(selectedProducts, function(productId,numberOfItems){ var productInfo = $this.getProduct(productId); html += '<tr id="' + productId + '"><td>' + productInfo.name + '</td><td>' + (productInfo.price) + '</td><td>'+ numberOfItems + '</td><td>' + (productInfo.price * numberOfItems) + '</td><td><button class="remove">Remove</button></td></tr>'; total += productInfo.price; }); html += '</table>'; html += '<br /><br />Grand Total:' + total; $('#cartItems').empty(); $('#cartItems').append(html); } this.getProduct = function(productId) { var found = {}; $.each( products, function(id, product){ if( product.id == productId) { found = product; return false; } }) return found; } } var PM = new productManagement(); PM.delegate(); PM.displayProducts(); }) 
  .header { background-color:#E0E8FF; padding:5px; text-align:center; } .content { padding-left:15%; padding-top:40px; width:100%; overflow:auto } .cart { padding-left:15%; padding-top:40px; width:100%; } .footer { background-color:#E0E8FF; text-align:center; } .item { width:25%; height:150px; overflow:auto; border:1px solid black; float:left } 

The function which you are calling is not exist in the context for delete when document loaded. By defining the function as global function, it is working.

/**
     * Class for handling general insert, update, delete 
     * oprations for a room booking system.
     */

    var bookingSystem = function (){
        this.editMode = false; 
        this.editIndex = false;

        // option data for Number of  persons drop down
        this.numPersonsOpts = [
            {name : 1, val : 1},
            {name : 2, val : 2},
            {name : 3, val : 3},
            {name : 4, val : 4}
        ];

        // Sample data to show initially
        this.bookingData = [
            {name : "John", roomType : "AC", numPersons : 3},
            {name : "Mishal", roomType : "Non AC", numPersons : 1}
        ];

        var self = this; // get a reference to this. 

        /**
         * Prepare and show options for dropdown
         * @param string selectorId id of the dropdown
         * @param object optionData array object contains name and value for the options 
         */
        this.showOptions = function (selectorId, optionData){
            var optsStr = "";
            for (var i=0; i<optionData.length; i++) {
                optsStr += '<option value='+optionData[i].val+'>'+optionData[i].name+'</option>';
            };
            document.getElementById(selectorId).innerHTML = optsStr;
        }

        /**
         * To save and update data
         */
        this.saveBooking = function (){
            var name = document.getElementById("bookingName").value;
            if(name){
                var singleEntry = {
                    name : name,
                    roomType : document.querySelector('input[name="roomType"]:checked').value == 1? 'AC' : 'Non AC',
                    numPersons : document.getElementById("numPersonSelect").value
                }
                if(self.editMode){
                    if(typeof(self.editIndex) == 'number'){
                        self.bookingData[self.editIndex] = singleEntry;
                        self.editIndex = false;
                    }
                    self.editMode = false;
                }else{
                    self.bookingData.push(singleEntry);
                }

                document.getElementById("bookingName").value = '';
                self.renderTemplate();
            }   
        }
        /**
         * To edit a particular item
         * @param number index array index to edit
         */
        self.edit = function (index){
            self.editIndex = index;
            self.editMode = true;

            document.getElementById("bookingName").value = self.bookingData[self.editIndex].name;
            document.querySelector('input[name="roomType"][value="1"]').checked = self.bookingData[self.editIndex].roomType == 'AC'? true: false;
            document.querySelector('input[name="roomType"][value="2"]').checked = self.bookingData[self.editIndex].roomType == 'Non AC'? true: false;
            for(var i=0; i<this.numPersonsOpts.length; i++){
                document.getElementById("numPersonSelect").options[i].selected = false;
            }
            document.getElementById("numPersonSelect").options[(self.bookingData[self.editIndex].numPersons)-1].selected = true;
        }

        /**
         * To delete a particular item
         * @param number index array index to delete
         */
        self.deleteItem = function (index){
            console.log("called once");
            self.bookingData.splice(index,1);
            self.renderTemplate();
        }

        /**
         * To preapre table content and show it.
         */
        this.renderTemplate = function (){
            var template = '';  
            if(self.bookingData.length > 0){
                for(var i= 0; i< self.bookingData.length; i++){
                    template += '<tr>';
                    template += '<td>'+self.bookingData[i].name+'</td>';
                    template += '<td>'+self.bookingData[i].roomType+'</td>';
                    template += '<td>'+self.bookingData[i].numPersons+'</td>';
                    template += '<td><button type="button" onclick = "return callEdit('+i+')">Edit</button></td>';
                    template += '<td><button type="button" onclick = "return callDelete('+i+')">Delete</button></td>';
                    template += '</tr>';
                }
            }else{
                template += '<tr>';
                template += '<td colspan="2"> No Data Found.</td>';
                template += '</tr>';
            }
            document.getElementById("renderTable").innerHTML = template;
        }


        this.init= function(){
            console.log("called");
            self.showOptions('numPersonSelect',self.numPersonsOpts); // Show number of persons option

            // Save Button event
            var btn = document.getElementById("saveBookingBtn");
            if(btn.addEventListener){
                btn.addEventListener('click',self.saveBooking);
            }else{
                btn.attachEvent('onclick',self.saveBooking);
            }

            self.renderTemplate();
        }



    }


    var bs = new bookingSystem(); // Create object for bookingSystem
        bs.init();

    window.callEdit = function(index){
        bs.edit(index);
    }

    window.callDelete = function(index){
        bs.deleteItem(index);
    }

check this example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM