【问题标题】:Adding object to array using controllers model使用控制器模型将对象添加到数组
【发布时间】:2015-10-31 14:13:06
【问题描述】:

您好,我正在尝试使用 ember 将对象添加到数组中。 Friends 控制器模型返回一个对象数组(App.friends)。

从朋友/新模板中,我得到了用户的名字、姓氏和关于他们的信息。

一旦我得到用户点击创建并通过使用 ember 的需求功能从 FriendsNewController 内部访问 App.friends 将信息添加到 App.friends。

由于某种原因,当我单击创建时出现以下错误,

未捕获的类型错误:desc.get 不是函数

App.FriendsRoute = Ember.Route.extend({
    model: function(){
        return App.friends;
    }
});


App.FriendsNewController = Ember.Controller.extend({
    needs: "friends",
    isInvalid: true,

    validForm: function(){

        if(this.get('lastName') && this.get('firstName')){
            this.set("isInvalid", false);
        } else {
            this.set("isInvalid", true);
        }

    }.observes('firstName','lastName'),

    actions: {
        create: function(){
            var newFriend = Ember.copy(this.content);
                this.get('controllers.friends.model').addObject(newFriend);
            this.transitionToRoute('friends');
        }
    }
});

  <script type="text/x-handlebars" id="friends/new">
    <label>First Name</label>
    {{input value=firstName}}<br />

    <label>Last Name</label>
    {{input value=lastName}}<br />

    <label>About</label>
    {{textarea value=about}}<br />

    <button {{action "create"}} {{bind-attr disabled=isInvalid}}>Create</button>

  </script>

      App.friends = [
    {id: 1, firstName: "John", lastName: "Joe", about: "Funny"},
    {id: 2, firstName: "Mary", lastName: "Joey", about: "Smart"},
    {id: 3, firstName: "Henry", lastName: "Jim", about: "Kind"}
];

我对 Ember 非常陌生,所以请随时将我推向正确的方向。谢谢:)

【问题讨论】:

    标签: javascript arrays ember.js


    【解决方案1】:

    看来你是在正确的轨道上。

    在以下行中,您尝试将对象添加到控制器:

    this.get('controllers.friends').addObject(newFriend);
    

    但它应该被添加到一个数组中:

    this.get('controllers.friends.model').addObject(newFriend);
    

    App.friends 是什么?要让addObject 工作,它应该是一个 Ember 数组(不是普通数组,即 [1,2]Ember.A([1,2])

    【讨论】:

    • 我也改了.model,我之前也试过,但没有解决问题,你说的是Ember数组,我如何定义一个?我添加到定义数组的代码中
    • 你能告诉我你定义数组的代码吗?
    • 好的 :) 尝试以下操作:App.friends = Ember.A([ {id: 1, firstName: "John", lastName: "Joe", about: "Funny"}, {id: 2, firstName: "Mary", lastName: "Joey", about: "Smart"}, {id: 3, firstName: "Henry", lastName: "Jim", about: "Kind"} ])
    • 告诉我。如果它不起作用,我将设置一个示例应用程序,看看发生了什么!
    • 我交换了获取 ember.js 文件的位置,以某种方式解决了问题,尽管它附加了一个看似空的对象,这是一个单独的问题
    猜你喜欢
    • 2020-11-04
    • 2021-07-04
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多