Frrout
Frrout

Reputation: 13

How to edit an array from a textarea in Ember js?

I'm trying to update an array from a textArea, each line of which would be a new item. Here is what I tried to do, but the textArea doesn't update the array:

Handlebars:

<script type="text/x-handlebars">
    {{view Ember.TextArea valueBinding="App.listController.formattedContent"}}
    </br>
    {{#each App.listController}}
        {{this}}
    {{/each}}
</script>

JavaScript:

App = Ember.Application.create({});

App.listController = Ember.ArrayController.create({
    content: ['some', 'items', 'in', 'an', 'array'],
    formattedContent: function() {
        return this.get('content').join('\n');
    }.property('content')
});

and the jsFiddle I know it can't be that simple, but I have no idea where to start. Any idea?

Upvotes: 1

Views: 741

Answers (2)

PaddyDwyer
PaddyDwyer

Reputation: 475

The accepted answer doesn't work with ember-1.0.0-rc3.

Computed properties can have setters now so the example in the question would be changed to

JS Bin: http://jsbin.com/iworub/2/

Handlebars:

<script type="text/x-handlebars" data-template-name="application">
  {{outlet}}
</script>

<script type="text/x-handlebars" data-template-name="index">
   {{view Ember.TextArea valueBinding="formattedContent" rows="7"}}
  </br>
  {{#each content}}
    {{this}}</br>
  {{/each}}
</script>

JavaScript:

App = Ember.Application.create({});

App.IndexRoute = Ember.Route.extend({
  setupController: function(controller) {
    controller.set('content', ['some', 'items', 'in', 'an', 'array']);
  }
});

App.IndexController = Ember.ArrayController.extend({
  formattedContent: function(key, value) {

    //getter
    if (arguments.length === 1) {
      return this.get('content').join('\n');

    //setter
    } else {
      this.set('content', value.split('\n'));
    }
  }.property('content')
});

Upvotes: 0

Panagiotis Panagi
Panagiotis Panagi

Reputation: 10077

Here you go:

Fiddle: http://jsfiddle.net/Sd3zp

Ember Controller:

App.listController = Ember.ArrayController.create({
    content: ['some', 'items', 'in', 'an', 'array'],

    init: function() {
        var content = this.get('content');
        if(content.length > 0){
           this.set('rawContent', content.join('\n'));
        }            

        this._super();
    },

    rawContentDidChange: function(){
       var rawContent = this.get('rawContent');

       var content = rawContent.split('\n');
       this.set('content',content);
    }.observes('rawContent'),
});​

Handlebars template:

<script type="text/x-handlebars">
  {{view Ember.TextArea valueBinding="App.listController.rawContent" rows="5"}}
  <br />
  <br />
  <strong>Output listController content items:</strong>
  {{#each App.listController.content}}
     {{this}} <br />
  {{/each}}
</script>

Upvotes: 3

Related Questions