在init函数中设置的控制器总是相等的

Lux*_*Lux 7 ember.js

我有一个Ember.Controller,在init函数中使用setup-code.实际上,这段代码会产生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'));


?
Run Code Online (Sandbox Code Playgroud)

Mik*_*ski 18

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

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

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

    // other setup here...
  }
});
Run Code Online (Sandbox Code Playgroud)

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

  • 另外不要忘记在自定义`init`函数中调用`this._super();` (6认同)