Backbone.js collection.create函数不会使用wait:true返回更新的模型

时间:2014-08-08 03:02:49

标签: javascript backbone.js laravel-4

在Laravel 4中使用Backbone.js时,我使用带有wait:true选项的this.collection.create()插入数据库。它插入到数据库中是正常的,但是如果设置了wait:true,它就不会更新模型。因此,如果我再次尝试输出集合,即使尝试成功回调函数返回一个值并且POST请求返回正数,它也不会更新。

该应用是一个联系人管理系统。 这是我的联系模式:

App.Models.Contacts = Backbone.Model.extend({

});

这是我添加联系人的视图

App.Views.AddContact = Backbone.View.extend({
el: '#addContact',
events: {
    'submit': 'addContact',
},
initialize: function() { // cache values
    this.first_name = $('#first_name');
    this.last_name = $('#last_name');
    this.email_address = $('#email_address');
    this.description = $('#description');
},
addContact: function(e) {
    e.preventDefault();
    this.collection = this.collection.create({
        first_name: this.first_name.val(),
        last_name: this.last_name.val(),
        email_address: this.email_address.val(),
        description: this.description.val(),
    }, { wait: true });

},
});

这是集合:

App.Collections.Contacts = Backbone.Collection.extend({
model: App.Models.Contacts,
url: '/projects/gamesapp/public/contacts',
});

这是页面上的脚本,将所有这些付诸行动:

<script>
    new App.Router;
    Backbone.history.start();

    App.contacts = new App.Collections.Contacts;
    App.contacts.fetch().then(function() {
        new App.Views.App({ collection: App.contacts });
    });
</script>

我能做些什么才能让这个工作?我希望在视图中创建以在本地更新模型,这似乎不是。

谢谢!

1 个答案:

答案 0 :(得分:0)

问题不在js或骨干代码中,而是在我写的Laravel代码中。

似乎POST返回了一个肯定的响应和所有,但问题出在我的控制器的存储方法中,你必须从store()函数返回create()函数! ,说清楚:

public function store()
{
    $input = Input::all();

    return Contact::create(array( // YOU HAVE TO RETURN SOMETHING
        'first_name' => $input['first_name'],
        'last_name' => $input['last_name'],
        'email_address' => $input['email_address'],
        'description' => $input['description'],
    ));

}

我的问题是因为我没有返回它,只是调用Contact :: create()函数...(联系人是Laravel模型)