3

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.

Jinghui Niu
  • 990
  • 11
  • 28

2 Answers2

0

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)

Facundo La Rocca
  • 3,786
  • 2
  • 25
  • 47
  • I've heard something bad about .bind(), is it considered bad practice in Javascript? – Jinghui Niu Dec 01 '16 at 03:50
  • By the way, your second way doesn't work, as this there refers to the Window object. For the first way, where should that line go? Inside a prototype. – Jinghui Niu Dec 01 '16 at 03:55
  • Wow, I'm sure we could find too many opinions in favor, and the too many opinions against. I think firstly you should understand how the context and 'this' work in JS, maybe you dont need to declare _renderList into that object, and bind take no place at all. Does 'bind' work? – Facundo La Rocca Dec 01 '16 at 03:59
  • To use the first way you must use a constructor, that means you need to use ES6 and use class declaration. – Facundo La Rocca Dec 01 '16 at 04:01
0

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();
Tolgahan Albayrak
  • 3,118
  • 1
  • 25
  • 28