Jinghui Niu
Jinghui Niu

Reputation: 1140

Javascript: How to reference the owner of the owner object inside a options object like this?

I wrote a jQuery UI widget like this:

$.widget("ns.wid", {
    options: {
        attr1: "something1",
        attr2: {
             "sub_attr": this.__renderList,
             "css": {
                "opacity": '0.58'
              },
        },
    },

    __renderList: function() {
       console.log("I should be invoked through attr2.sub_attr!");
    }
});

Now it's not working, as the this inside attr2 does not reference to the widget instance, instead it references the Window. How can I reference to the widget instance without directly naming it? Thanks.

Upvotes: 3

Views: 341

Answers (2)

Tolgahan Albayrak
Tolgahan Albayrak

Reputation: 3206

I'm not sure if non-plain objects will work properly with jQuery's widgets but. you can try this.

var widgetData = (new class {
    get options() {
        return {
          attr1: "something1",
          attr2: {
             "sub_attr": this.__renderList,
             "css": {
                "opacity": '0.58'
              },
          },
       };
    }

    __renderList() {
       console.log("I should be invoked through attr2.sub_attr!");
    }
});

widgetData.options.attr2.sub_attr();

Upvotes: 0

Facundo La Rocca
Facundo La Rocca

Reputation: 3876

In the contructor of your object bind the function to its context lke this: this._renderList = this._renderList.bind(this)

Or just: "Sub_att": this._renderList.bind(this)

Upvotes: 0

Related Questions