7

我有一个Ember.Controller, 在 init 函数中有设置代码。实际上,此代码发出 AJAX 请求。但是当我创建这个控制器的两个实例时,它们总是相等的。为什么,我该怎么做呢?

我做了这个简单的例子,应该写入Test 1 Test 2控制台。把它的字咬了Test 2两下。

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'));


​
4

1 回答 1

18

您必须在 中设置contentinit,否则在类声明时设置的值将由所有实例共享。

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

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

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

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

于 2012-07-18T13:21:07.280 回答