Tom Rider
Tom Rider

Reputation: 2815

How to create a constructor in javascript

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();
        }

 }

Upvotes: 0

Views: 152

Answers (2)

CodeWizard
CodeWizard

Reputation: 142114

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(){...},

}

Upvotes: 2

Tallmaris
Tallmaris

Reputation: 7590

Try this:

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

or:

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

Upvotes: 4

Related Questions