【问题标题】:Ember JS cannot createRecord with new ember-data syntaxEmber JS 无法使用新的 ember-data 语法创建记录
【发布时间】:2013-11-08 02:33:25
【问题描述】:

我正在尝试使用新的 ember-data 语法,如下所述:https://github.com/emberjs/data/blob/master/TRANSITION.md(从 Transaction is Gone: Save Individual Records 读取)。

当我点击保存按钮时,我在控制台中收到错误 Uncaught TypeError: Cannot call method 'save' of undefined。同样在网络选项卡中,没有对 api 的 POST 请求。

模板

<script type="text/x-handlebars" data-template-name="landcode/new">
    Code: {{input value=code}}<br />
    Image: {{input value=image}}<br />
<button {{action 'saveLandcode'}}>opslaan</button>

app.js(相关代码)

App.Router.map(function() {
    this.resource("landcodes"),
    this.resource("landcode", function() {
        this.route("new");
    });
});

App.LandcodeNewRoute = Ember.Route.extend({
    model: function() {
        this.store.createRecord('landcode');
    },
    actions: {
        saveLandcode: function(){
            this.modelFor('landcode').save(); // does not save
        }
    }
});

App.ApplicationAdapter = DS.RESTAdapter.extend({
    namespace: 'api'
});
App.Store = DS.Store.extend({
    adapter: 'App.ApplicationAdapter'
});

App.Landcode = DS.Model.extend({
    code: DS.attr('string'),
    image: DS.attr('string')
});

【问题讨论】:

    标签: ember.js ember-data


    【解决方案1】:

    您使用的是this.modelFor('landcode'),这将从App.LandcodeRoute 获取返回的模型,但您的模型是从LandcodeNewRoute 返回的。只需使用this.currentModel,因为您想要当前路线的模型。

    App.LandcodeNewRoute = Ember.Route.extend({
        model: function() {
            return this.store.createRecord('landcode');
        },
        actions: {
            saveLandcode: function(){
                this.currentModel.save();
            }
        }
    });
    

    【讨论】:

    • 都感谢您的回答。然而,这两种解决方案都给出了与以前相同的错误。我去设置一个jsFiddle,然后每个人都会清楚这是怎么回事。
    • 我在您的代码中看到您在 this.store.createRecord 中缺少return ...您是否更新了当前的实现?
    • 嗨马尔西奥,感谢您的最后评论!死了,我错过了你添加的返回声明。我删除了我最后的 JS Bin 评论,顺便说一下,在 jsFiddle 或 JS Bin 上设置 Ember.js 应用程序是一项非常不愉快的活动。现在我们已经找到了错误,再次感谢!
    【解决方案2】:

    你的模型也应该包含路由名称

    App.LandcodeNewRoute = Ember.Route.extend({
        model: function() {
            return this.store.createRecord('landcode');
        },
        actions: {
            saveLandcode: function(){
                this.modelFor('landcode.new').save(); // the correct model
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-09
      • 2015-12-04
      • 2015-07-02
      相关资源
      最近更新 更多