GrandMarquis
GrandMarquis

Reputation: 1913

Ember.js Binding value to JSon object

I'm trying to bind an input value to a JSon object but I can't find a way to make it work.

Here is a sample of my object.

Data = {
    value = "test"
};

and my App.FIXTURES

App.FIXTURES = [
    {
       title : "What is your age?",
       linkedTo : Data.value
    }
];

And my template:

 {{#each questions}}
     {{title}}
     {{input type="text" valueBinding=linkedTo}}
 {{/each}}

The binding works only in one way, it retrieve the value to display but when I try to access the Data.value field it never change.

Is it possible to do this? I tried several ways without success. Do I have to extend the Ember.Textfield? If yes, how would you implement this?

Thank you,

Upvotes: 0

Views: 301

Answers (3)

GrandMarquis
GrandMarquis

Reputation: 1913

Thanks to tavi, I came with an new idea of getting my problem solved.

I created a new custom view extending the Ember.TextField:

App.CustomTextField = Em.TextField.extend({
    keyUp:function(event){
        console.log(this.get('value'));
        //Watch input for Security code injection!!
        eval(linkedto + ' = this.get(\'value\')');
    }
});

So everytime I update the value it is fully synchronized between my textfield and json.

Upvotes: 0

tavi
tavi

Reputation: 594

Even if what kingpin2k is true I have a suggestion in case you still want to achieve this kind of functionality. So try and use an object whose key to change instead of the actual string value.

What I mean is that instead on using the actual string to bind to, use instead an object and bind to a property. So instead of using Data.value string value directly you will use Data.value as an object with a key actualValue that will hold the string's value. Now ember can set up it's magic to bind to this property and change the value.

So when you want to get the Data.value string value you instead go for Data.value.actualValue which is bound to the linkedTo.actualValue

So your code would become:

var Data = {
  value: {
    actualValue: 'test'
  }
};

App.FIXTURES = [
  {key: 'red', linkedTo: Data.value}
];

In the template:

{{input type="text" valueBinding=linkedTo.actualValue}}

And where you will get the value:

el.innerHTML = Data.value.actualValue + '<br/>' + el.innerHTML;

Here is a demo of the things I tried to explain emberjs jsbin

Upvotes: 1

Kingpin2k
Kingpin2k

Reputation: 47367

Javascript strings are immutable. You're essentially copying the value "test" to linkedTo not linking it up to Data.value

Upvotes: 1

Related Questions