我使用Ember应用程序创建了一个模型,但我试图向该模型添加一条记录,但我不断收到错误消息,指出undefind不是函数。

window.Aplus = Ember.Application.create();

Aplus.Store = DS.Store.extend();

Aplus.ApplicationAdapter = DS.Adapter.extend({
  createRecord: function(store, type, record) {
    var data = this.serialize(record, { includeId: true });
    var url = type;

    return new Ember.RSVP.Promise(function(resolve, reject) {
      jQuery.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: data
      }).then(function(data) {
        Ember.run(null, resolve, data);
      }, function(jqXHR) {
        jqXHR.then = null; // tame jQuery's ill mannered promises
        Ember.run(null, reject, jqXHR);
      });
    });
  }
});


Aplus.Router.map(function () {
  this.resource('aplus', function() {
    this.route('agents');
  });
});

Aplus.Agent = DS.Model.extend({
  firstname: DS.attr('string'),
  lastname: DS.attr('string'),
  team: DS.attr('string'),
  position: DS.attr('string'),
  email: DS.attr('string'),
});

Aplus.AplusRoute = Ember.Route.extend({
  model: function() {
    var agentObjects = [];
    Ember.$.getJSON('/agents', function(agents) {
      console.log(agents);
      agents.forEach(function(agent) {
        console.log(agent);
        console.log(Aplus.Agent.createRecord({
          id: 1,
          firstname: 'Edmond',
          lastname: 'Dantes',
          team: 'all',
          position:'count',
          email: '[email protected]'
        }).save());
        //agentObjects.pushObject(Aplus.Agent.createRecord(agent));
      })
    });
    return agentObjects;
  }
});


代码在我执行Aplus.Agent.createRecord({})的行上中断。我尝试将其更改为this.store.createRecord({}),但收到一条错误消息,提示无法读取未定义的属性createRecord。路由代理与我的节点路由链接并获取正确的数据。

为什么这不起作用?另外为什么this.store.createRecord返回的存储区是未定义的,我认为可以通过扩展DS.Store来定义它,而createRecord将在applicationAdapter的扩展名中定义,不是吗?

我以为我的链接可能是旧的,但我使用了这些CDN,我认为这些是更新的版本

<script src="http://emberjs.com.s3.amazonaws.com/getting-started/jquery.min.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/2.0.0/handlebars.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ember.js/1.9.1/ember.js"></script>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ember-data.js/1.0.0-beta.14.1/ember-data.min.js"></script>


任何帮助将非常感激。

最佳答案

您在getJSON函数中失去了它的上下文,请在输入函数var self = this;然后调用self.store.createRecord({})之前对此进行引用

Aplus.AplusRoute = Ember.Route.extend({
  model: function() {
  var agentObjects = [];
  var self = this;
  Ember.$.getJSON('/agents', function(agents) {
  console.log(agents);
  agents.forEach(function(agent) {
    console.log(agent);
    console.log(self.store.createRecord('agent', {
      id: 1,
      firstname: 'Edmond',
      lastname: 'Dantes',
      team: 'all',
      position:'count',
      email: '[email protected]'
    }).save());
   })
  });
 return agentObjects;
 }
});

09-20 14:48