Question

I'm learning how to use objects to help organize my code and give it some structure but I've run into a problem. I don't understand how to set the $(this) from inside of one function to the $(this) of another function.

I'm researching call and apply but I can't seem to grasp how it works in this scenario.

cloneCard and clickCard is where I'm having the problem. I want to pass the $(this) that is referenced when I click the card to the cloneCard function.

Here is my code so far (updated to reflect the answer):

var Modal = {
            init: function(config) {
                this.config = config;
                this.clickCard();
                this.removeModal();
                this.clickOutside();
                this.createClose();
            },
            clickCard: function() {
                $this = this;
                this.config.boardOutput.on('click', '.card', function(event) {
                    $this.showOverlay();
                    $this.cloneCard.call($(this));
                    $this.createClose();
                });
            },
            cloneCard: function() {
                this.clone()
                    .replaceWith($('<div/>').html(this.html()))
                    .removeClass('card')
                    .addClass('modal')
                    .css("margin-top", $(window).scrollTop())
                    .prependTo('body');
            },
            showOverlay: function() {
                this.config.overlay.show();
            },
            removeModal: function() {
                $('.modal').remove();
                $('.overlay').hide();
            },
            clickOutside: function() {
                this.config.overlay.on('click', this.removeModal);
            },
            createClose: function() {
                $('<span class="close">X</span>')
                    .prependTo('.modal')
                    .on('click', this.removeModal);
            }
        };

        Modal.init({
            boardOutput: $('#board-output'),
            overlay: $('.overlay')
        });
Was it helpful?

Solution

For what you need, calling self.cloneCard.call($(this)); instead of self.cloneCard($(this)); should work. What you're doing is, calling cloneCard passing it the element in which the the clickCard event occured.

If this doesn't work, i think we'll need more information to sovle your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top