Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controllers with setup in init function are always equal

Tags:

ember.js

I've an Ember.Controller, with setup-code in the init function. In reality this code makes AJAX requests. But when I create two instances of this controller, they are always equals. Why, and what can I do again this?

I've made this simple example, which shoud write Test 1 Test 2 into the console. Bit its writing Test 2 twice.

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

App.TestController = Em.Controller.extend({
    content: Em.Object.create({
        info: null,
    }),
    init: function() {
        if(this.id == 1)
        {
            this.content.set('info', "Test 1");
        }

        if(this.id == 2)
        {
            this.content.set('info', "Test 2");
        }
    },
});

var c1 = App.TestController.create({id: 1});
var c2 = App.TestController.create({id: 2});

console.log('C1: ' + c1.get('content').get('info'));
console.log('C2: ' + c2.get('content').get('info'));


​
like image 318
Lux Avatar asked Jul 18 '12 13:07

Lux


1 Answers

You have to set content value in init, otherwise, the value set at class declaration time will be shared by all instances.

App.TestController = Em.Controller.extend({
  content: null,

  init: function () {
    this._super();
    this.set('content', Em.Object.create({
      info: null
    }));

    // other setup here...
  }
});

See http://codebrief.com/2012/03/eight-ember-dot-js-gotchas-with-workarounds/

like image 104
Mike Aski Avatar answered Jan 04 '23 21:01

Mike Aski