0

Within my AngularJS service I'm trying to call method within the same file within a $http success block and I have to use 'that = this' so I can access it properly.

calc_total: (line) ->
  that = this
  $http.get("/item/get_cost?costing_id=" + line.costing_id).then (
    (response) ->
      # If successful set the cost per unit cents
      line.cost_cents = response.data['cost_cents']
      that.accumulated_balance(line) # Update balance
  )

What is the correct way of doing this?

1
  • This works, but is there a way to pass in 'this' into the http block so that I can access it? I think the 'that = this' code is messy. Commented Jul 7, 2015 at 3:14

1 Answer 1

1

You can use the fat arrow => to preserve the this from the calc_total closure:

calc_total: (line) ->
  $http.get("/item/get_cost?costing_id=" + line.costing_id).then (
    (response) =>
      # If successful set the cost per unit cents
      line.cost_cents = response.data['cost_cents']
      this.accumulated_balance(line) # Update balance
  )

See this guide for reference.

The JavaScript ES5 equivalent is

function () {}.bind(this);

The fat arrow syntax made its way into ES6 as well.

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

Comments

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.