简体   繁体   中英

JavaScript - How to get the name of the key inside a function

I have a javascript literal object as shown below..

var db = new Observer();
var user = {
   firstName: db.observe("abc"),
   lastName: "xyz",
   middleName: db.observe("test")
};

NOTE: the "firstName" value is a function call db.observe("abc") which takes a parameter.

var Observer = function() {
    this.observe = function (value) {  // INITIAL value of the field
        // HOW WILL I GET "key, for e.g. firstName" key here so that i can associate "value" with it.

    return this;
    }
}

My requirement is to get the name of the key, in this case 'firstName" in the observe() function.

OR Please feel free to recommend alternatives to achieve the same.

NOTE: This is related to a small MVVM framework which I am experimenting with and am stuck at this point.

Let me know whether this is possible with JS.

REF: knockoutjs does something like this... http://knockoutjs.com/examples/helloWorld.html

You have to provide that type of information to the interface of the function:

var observation = db.observe("abc");
var other_observation = db.observe("test");
var user = {
   firstName: ( todayIsFriday ? observation : other_observation ),
   lastName: "xyz",
   middleName: ( todayIsFriday ? other_observation : observation )
};

You can't really expect the parser to know what to use as "key" here in the observe function, you'd basically need to implement a time machine in Javascript first.

So, you really need to pass it as an extra parameter, or put your db object in a sort of "state" first.

you can achive by for..in . see the demo below

http://jsfiddle.net/3SwyM/2/

although its works on static names, but if your observe() works well then you can achieve the result also

Answering my own question as i just got a my sample ready. Thanks to Yoshi's comment, which probed me to dig deeper..

I am posting the link to sample implementation here, if anyone's interested... The code is buggy but demonstrated data binding which I was trying to do POC...

Here is the jsfiddle URL...

http://jsfiddle.net/rajeshpillai/xQkXk/22/

Try changing the value in the textbox, the dependent objects are automatically updated....

Thanks all for the comment. This is just raw/buggy, code.. Will polish this over the next couple of days...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM