0

I am trying to create a constructor in javascript. This constructor is for deleteIcon. Whenever user hover any element and if i want to show a delete icon over that element than i am using this constructor. But i am pretty new in this approach and i want to create a click event also in the constructor . Can anyone please guid me how to do this ?

function deleteIcon(el)
{
        var self = this;
        self.button = $("<button type='button' id='removemyparent' />");

        self.element = el;

        self.add = function () {
            var widths = $(self.element).children().map(function () { return $(this).width(); });
            var maxWidth = max(widths);

            self.button.button({ text: false, icons: { primary: "ui-icon-close" } });
            $(self.element).append(self.button);

            self.button.css({ position: "absolute", top: 0, left: maxWidth - self.button.width() });
        }

        self.remove = function () {
            $(self.element).find("#" + self.button.attr("id")).remove();
        }

        self.button.click = function () {            //this is not working
            self.element.remove();
        }

 }
4
  • 1
    click is a jQuery method not a property. Also, you're setting a static ID that is going to be used for all instances of deleteIcon... set a class instead. Commented Oct 18, 2012 at 8:22
  • @ahren can you tell me the better approach to implement click event in the constructor for the deleteIcon Commented Oct 18, 2012 at 8:23
  • 1
    the same way you do with any other jQuery object... .click(function(){}); Commented Oct 18, 2012 at 8:25
  • @Tom Rider "can you tell me the better approach to implement […]" Yes, read the documentation – it really helpful. Why does your title not relate to the question? Where is that part of code you need a constructor for? Commented Oct 18, 2012 at 8:33

2 Answers 2

4

Try this:

self.button.click(function () { self.element.remove(); })

or:

self.button.on('click', function () { self.element.remove(); })
Sign up to request clarification or add additional context in comments.

Comments

2

There are few ways you can create constructor in JS.

the most easy and clear way is this one:

// Constructor
var MyObj=function(){ .... }

MyObj.prototype = {
    constructor : MyObj,
    button: function(){...},
    add: function(){...},

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.