在ajax事件中将模型添加到关系模型的集合中

时间:2012-01-10 20:24:54

标签: backbone.js backbone-relational

我有食谱模型,食谱有一个成分列表集合,存储一堆成分。

当我从表单提交中将成分添加到成分列表中时,我必须从服务器获取“id”,因此我执行ajax请求,获取id,然后尝试将成分添加到模型。

在我的ingredientlist.view中,我有

    initialize: function(){
        this.recipe = this.model;
        },

         get_ingredient: function(ingredient){
            var ingredient_id = new MyApp.Models.Ingredient;
        ingredient.url='/ingredients/?ing='+encodeURIComponent(ingredient_array[i]);

        ingredient.fetch({

            success: function() {
                this.recipe('add:ingredients', function(ingredient,ingredientlist){

                });
            },
            error: function() {
                new Error({ message: "adding ingredient" });
            }
        });
        }

我没有包含触发'get_ingredient'的函数,因为我得到ajax很好,所以问题不在于触发'get_ingredient'。

我收到错误Uncaught TypeError: Property 'recipe' of object [object DOMWindow] is not a function 使用现有代码。

完成这样的事情的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

首先,我也是使用backbone.js的新手! 所以我的想法是:

  • 你需要在你的视图中绑定你的get_ingredient:看bind来触发你的功能!
  • 尝试将Context(this)传递给“get_ingredients”

这只是我的5美分