0

Basically I'm trying to use this package pullToRefresh in my Angular application.

The code is as follows

const ptr = pullToRefresh.init({
                mainElement: '.dashboard-container',
                onRefresh() {
                    console.log('pulled');
                    // this._service.action();
                }
            });

now obviously the this is not going to work since this now refers to the onRefresh() callback function. So my question is how can I correctly bind this to use it correctly within that callback function onRefresh

now I have tried to just change the callback to an arrow function like so

onRefresh = () => {...

but my tslint says '=' can only be used in an object literal property inside a destructuring assignment.

any help would be appreciated

2 Answers 2

2

You could try using an arrow function so onRefresh does not create it's own scope, like so:

const ptr = pullToRefresh.init({
    mainElement: '.dashboard-container',
    onRefresh: () => {
        console.log('pulled');
        // this._service.action();
    }
});

Read more about arrow functions here.

Sign up to request clarification or add additional context in comments.

3 Comments

my tslint '=' can only be used in an object literal property inside a destructuring assignment. I should of been more specific I did try using an arrow function already I will update my question
There was a typo in the code I posted. It's fixed now.
Glad to hear! Accept the answer please :)
1

For this, you can bind this to your callback function.

pullToRefresh.init({
  mainElement: '.dashboard-container',
  onRefresh() {
    console.log('pulled');
    // this._service.action();
  }.bind(this)
})

Alternatively, you may try this:

const that = this;
const ptr = pullToRefresh.init({
  mainElement: '.dashboard-container',
  onRefresh() {
    console.log('pulled');
    that.service.action();
  }
});

4 Comments

My VSCode doesn't like this it says ',' expected
Hmm... Ok honestly I am not too sure about that too. How about binding this on the init? pullToRefresh.init({...}).bind(this)? Also, I have initially added the ; at the end of the onRefresh{...}.bind(this). That might have have caused the warning on your VSCode
No that didnt work either I got a webpack error ERROR TypeError: pulltorefreshjs__WEBPACK_IMPORTED_MODULE_8__.init(...).bind is not a function
I see.. Ok let me update it with the old school way.. Assigning that with the reference of this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.