3

I am trying to do something like

var foo = {
    bar: '' // do some magic here
};

and only WHEN i need to use the value (later on the page) just simply call the property will run a lazy load and send back the value

The typical exemple is that I have a restfull API that load a user on page opening. After going to a menu I want to access the property related to it (another object), but it's in another api, and I don't want to load all at the opening.

Is there some kind of listener on property call ?

4
  • 2
    I think you'll have to use some getters(/setters) here (probably with caching) Commented Aug 1, 2013 at 14:48
  • simple answer? nop... And I don't think it would be very good practice to implement this is JS for your use case... Commented Aug 1, 2013 at 14:48
  • @NickyDeMaeyer Is there a particular reason to not use this in this use case ? Commented Aug 1, 2013 at 15:12
  • not really, it would just become very complex (ORMs often use the technique), and your use case seems to have much simpler solutions, like the setters, getters solution. (the accepted answer is not very cross browser) Commented Aug 1, 2013 at 15:21

3 Answers 3

2

Use Object.definePropery to calculate foo.bar dynamically. It works in all modern browsers.

var foo = { };
Object.defineProperty(
    foo,
    "bar",
    {
        get: function () {
            return 'magic return value';
        }
    }
    );

JSFiddle: http://jsfiddle.net/wFYxb/

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

2 Comments

You can also cache the value within get() so that the api call is only made once.
@MukeshSoni sure, but there are cases where you want the property to return a different value upon every call.
1

If that is exactly what you want to do, all JavaScript objects in Firefox/Chrome/some others have the __defineGetter__ property that you can use to define lazy-calculated values.

> a.__defineGetter__('b', function () {return 'c';})
> a.b
"c"

Comments

1

Sounds like your property should just be a function definition, and you execute the function on demand:

var foo = {
   bar: function() { return goDoSomething(); }
};

foo.bar();

To save it, maybe a little more - populate another variable with the value and use it going forward once it's there.

var foo = new function () {
    var _bar;
    this.bar = function () {
        if (!_bar) {
            _bar = goDoSomething();
        }
        return _bar;
    }
} ();


function goDoSomething() {
    console.log("goDoSomething();");
    return 4;
}

2 Comments

Should be : instead of = after bar as this is object.
@antyrat Thanks, fixed. I'm in the C# anonymous type mindset right now.

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.