Click here to Skip to main content
15,895,557 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to do basic Crud operation in JavaScript and I am having some difficulty. Let me explain by showing you the code:

HTML
<html>
    <head>
        <title></title>
    </head>
<body>
    <input id="name" type="text" value="" />
    <input id="Add" type="button" value="Add" />
   
    <div id="userList" ></div>

<script type="text/javascript" src="../Scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
    $(function ($) {
        var User = function (name) {
            this.Name = name;
            this.Delete = function () {
                // this will be button element
                alert(this.Name);
                // how can I access the user element here ?
            }
        }

        $('#Add').click(function () {
            nUser = new User($('#name').val());
            $('#userList').append(GetViewTemplate(nUser));
        });

        function GetViewTemplate(user) {
            var del = $("<input type='button' value='Delete' />");
            // I am binding the click event of an instance method
            del.click(user.Delete);

            var li = $("<div>" + user.Name + "</div>");
            li.append(del);
            li.append("<br />");

            return li;
        }

    });
</script>
 
</body>
</html>


I have a "User" class in JavaScript, which has a property "Name" and a Function "Delete".

When the Add button is clicked:
I am creating a user object and assigning text box value to Name property

JavaScript
var nUser = new User($('#name').val());


I am displaying the newly created user in a DIV where I am showing the Name and a "Delete" (created dynamically) button assigning the onclick function of the same to the user (obj) "Delete" function

JavaScript
var del = $("<input type='button' value='Delete' />");
del.click(user.Delete);


But when the "Delete" button is clicked I want to access the User instance and not the button element.

Is there any way to accomplish this ?
Posted

1 solution

You have just missed one step, the anonymous function:
del.click(function(){user.Delete()});
 
Share this answer
 
Comments
jaket-cp 11-Feb-15 7:30am    
in reference to the anonymous function :)
5ed
sandeshjkota 12-Feb-15 1:06am    
Well this solved the problem. But I am not sure why do we have to do this. Can you please shed some light ?
Peter Leow 12-Feb-15 3:17am    
According to http://api.jquery.com/click/
An event handler (such as an anonymous function) is required to bind to the click event(),
Putting "user.Delete" is amounting to a function call, not an event handler.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900