0

I have a base object ProfileDialog which I am extending with Object.assign().

var ProfileDialog = function (containerObj) {
    this.init = function () {
        this.container = containerObj;
    };

    this.render = function () {
        let content = document.createElement('div');
        content.innerText = 'Dialog here';
        this.container.appendChild(content);
    };

    this.init();
    this.render();
};

Mixin:

var DialogMixin = function () {
    return {
        open: function () {
            this.container.style.display = 'block';
        },
        close: function () {
            this.container.style.display = 'none';
        }

    }
};

Now I do the assignment:

Object.assign(ProfileDialog.prototype, DialogMixin());

It works just fine, this context resolves fine in open and close methods.

But, when I put the mixin in a deeper structure, putting it inside actions property:

var DialogMixin = function () {
    return {
        actions: {
            open: function () {
                this.container.style.display = 'block';
            },
            close: function () {
                this.container.style.display = 'none';
            }
        }
    }
};

The context becomes actions object so the code breaks.

How do I properly extend the object with new methods when they are put in a deep structure?

Sergei Basharov
  • 51,276
  • 73
  • 200
  • 335

1 Answers1

0

The only thing i can think of is using bind to bind this.

So something like

var ProfileDialog = function (containerObj) {
    this.containerObj = containerObj;
};

var DialogMixin = function (newThis) {
    var obj = {
        actions: {
            open: function () {
                console.log('open', this, this.containerObj.style);
            }
        }
    }
    obj.actions.open = obj.actions.open.bind(newThis);
    return obj;
};

var container = {
    style : 'some style'
};
var dialog = new ProfileDialog(container);
var mixinDialog = Object.assign(dialog, DialogMixin(dialog));

mixinDialog.actions.open();

See https://jsfiddle.net/zqt1me9d/4/

brass monkey
  • 5,841
  • 10
  • 36
  • 61