Ad

Pass The Context On To An Inner Function

- 1 answer

Here is the code:

function link(scope, element, attrs, formCtrl) {
    element.tooltipster({
        content: '',
        theme: 'validation-notify',
        arrowColor: '#d9534f',
        contentAsHTML: true,
        functionBefore: generateContent
    });
}

function generateContent() {
    var formField = formCtrl[element];
    var i = 0;
}

The above code is broken because formCtrl and element are not available in generateContent. Now, I realize that I could use:

functionBefore: generateContent.bind({formCtrl: formCtrl, element: element})

and then in generateContent I could reference them by

this.element

I could also just declare generateContent inside of link. Is there any better way of doing this? Like is there anyway of binding generateContent to the entire context within link, so something like:

functionBefore: generateContent.bind(this)

(except in this case this is undefined)?

Ad

Answer

Like is there anyway of binding generateContent to the entire context within link

Nope, the functions are lexically scoped and they remember the environment in which they are created. We cannot access those information, as they are implementation specific.

But what you can do is, make the generateContent function to accept all the parameters it needs and you can define functionBefore, like this

...
functionBefore: generateContent.bind(this, formCtrl, element)
...

function generateContent(formCtrl, element) {
    var formField = formCtrl[element];
    var i = 0;
}

Here, generateContent.bind(this, formCtrl, element) creates a new function object which when invoked, will have the context as the link function's this and two parameters formCtrl and element by default.

Ad
source: stackoverflow.com
Ad