【问题标题】:Ext JS: Load single database entry into modelExt JS:将单个数据库条目加载到模型中
【发布时间】:2013-12-30 20:42:12
【问题描述】:

我正在尝试创建一个具有单个数据库条目的模型,而不是只为一行创建一个存储...没有意义。无论如何,我可以使用static load method 创建模型,但是我的模型代理的 URL 是动态的,所以这不是一个选项,因为我只想动态加载。此外,创建模型的实例似乎不起作用,因为我无法使用 load 方法,因为它是静态的......

我已经开始尝试使用 Ajax 调用来获取数据,然后将其加载到模型的实例中,但是关联关系似乎没有被创建,即使是普通字段值也是如此。这就是我正在尝试做的:

代码

// SectionsModel
Ext.define('SectionsModel', {
  extend: 'Ext.data.Model',
  fields: ['name']
});

// MY_MODEL
Ext.define('MY_MODEL', {
  extend: 'Ext.data.Model',
  fields: ['name', 'id'],
  hasMany: [{
    associationKey: 'sections', name: 'getSections', model: 'SectionsModel'
  }],
  proxy: {
    type: 'memory',
    reader: {
      type: 'json',
      root: 'configuration'
    }
  }
});

var url = 'my/url';
Ext.Ajax.request({
  url: url,
  method: 'GET',
  scope: this,
  success: function(res) {
     var configObj = Ext.decode(res.responseText);
     var configModel = Ext.create('MY_MODEL', configObj);
     console.log(configModel);
  },
  failure: function(res) {
    console.error('failed');
  }
});

回应

{
  "code": 200,
  "configuration": {
    "name": "TestConfiguration",
    "id": 1,
    "sections": [{
       "name": "section1"
    }, {
       "name": "section2"
    }]
  }
}

上面的代码是我为这个例子编写的虚拟代码......如果它不起作用,则将其视为伪代码。就像我说的,当我使用静态 load method 时它确实有效,并且我可以成功地进行 Ajax 调用......问题是如何使用给定数据创建模型。我是否需要将 config 传递给模型的构造函数,并将模型的代理数据设置为传入的 config?这是正确的协议吗?我只是想在这里找出最好的方法。谢谢!

来自Sencha forums的交叉发布。

【问题讨论】:

    标签: ajax extjs model extjs4.2


    【解决方案1】:

    感谢 Mitchell Simoens 的blog post 之一,我想出了一个解决方案。我将 MY_MODEL 更改为如下所示:

    Ext.define('MY_MODEL', {
      extend: 'Ext.data.Model',
      fields: ['name', 'id'],
      hasMany: [{
        associationKey: 'sections', name: 'getSections', model: 'SectionsModel'
      }],
      constructor: function(data) {
        this.callParent([data]);
        var proxy = this.getProxy();
        if (proxy) {
          var reader = proxy.getReader();
          if (reader) {
            // this function is crucial... otherwise, the associations are not populated
            reader.readAssociated(this, data);
          }
        }
      },
      proxy: {
        type: 'memory',
        reader: {
          type: 'json'
        }
      }
    });
    
    // in the success of the Ajax call
    success: function(res) {
      var configObj = Ext.decode(res.responseText);
      var configModel = Ext.create('MY_MODEL', configObj.configuration);
      console.log(configModel);
    }
    

    【讨论】:

      猜你喜欢
      • 2021-06-30
      • 2016-08-23
      • 2013-09-14
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 2013-01-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多