Mike
Mike

Reputation: 6050

Create a setter for a local variable in a Javascript object

I have the following code

var loyaltyObject = (function () {
  var data = null, vm, getLoyaltyUrl;

  function getData() {
    $.ajax({
      type: 'POST',
      url: getLoyaltyUrl,
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      success: function (resp) {
        data = resp;
      },
      error: function (resp) {
        console.log('Error fetching offers!');
        console.log(resp);
      }// error(resp)
    });// $.ajax()  
  }

...

  vm = {
    getData: getData,
    getLoyaltyUrl: getLoyaltyUrl
  };

  return vm;
}());

on document.ready I call

function Init() {
    window.loyaltyObject.getLoyaltyUrl = '@Url.Action("GetLoyaltyData", "Orders")';
    window.loyaltyObject.getData();
}

window.loyaltyObject.getLoyaltyUrl is indeed the url but the internal getLoyaltyUrl is still undefined.

I read the following return a variable as a property about setting up a getter, but how would I perform a setter, what is the this or value I would be setting?

Also would it be comparable on most browsers?

Upvotes: 0

Views: 100

Answers (3)

T4rk1n
T4rk1n

Reputation: 1470

I don't think there's any need for a custom property here. But you can look into Object.defineProperty or it's Reflect counterpart to change objects properties on the fly.

Object.defineProperty(obj, 'getLoyaltyUrl', {
    set: (value) => {
        // do something here, better be worth it.
    },
    get: () => {}
})

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

You are assigning the value to vm.getLoyaltyUrl not to the private variable getLoyaltyUrl. That variable has no inheritance from the object vm so it never ever gets defined in your code

Just change:

url: getLoyaltyUrl

to

url: vm.getLoyaltyUrl

Simplified example

var loyaltyObject = (function () {
  var data = null, vm;

  function getData() {
   // switched out the ajax for a simple console.log()
   console.log(vm.getLoyaltyUrl)
  }

  vm = {
    getData: getData,
    getLoyaltyUrl: null
  };

  return vm;
}());
// following is exactly what you have
function Init() {
    window.loyaltyObject.getLoyaltyUrl = '@Url.Action("GetLoyaltyData", "Orders")';
    window.loyaltyObject.getData();
}

Init()

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816560

but how would I perform a setter, what is the this or value I would be setting?

You would simply assign to the variable getLoyaltyUrl:

vm = {
  // ...
  set getLoyaltyUrl(value) {
    getLoyaltyUrl = value;
  },
}

You wouldn't use this in your case. value is the value assigned to the property.

Upvotes: 1

Related Questions