骨干保存模型问题

时间:2013-04-11 16:59:11

标签: javascript backbone.js

我正在尝试保存模型并成功,取消它: 问题是,从成功内部我无法引用此引用(这是视图),我也无法引用this.model.save(...)返回的变量isOk.status。 代码:

save: function(e) {
    e.preventDefault();

    var isOk = this.model.save(null,
        {
            wait: true,

            success: function(model, response){
                console.log(response);
                console.log(response.status);

            },

            error: function(model, response){
                console.log("error");
                console.log($.parseJSON(response.responseText));
                $('#errorMessage').empty();
                $('#errorMessage').append($.parseJSON(response.responseText).error);
                $('#errorApproveModal').modal({
                    keyboard: true
                });
            }
        });
    console.log('logging isOk');
    console.log(isOk);
    //this one is working! It's on validate event
    if(!isOk){
        $('#errorMessage').empty();
        $('#errorMessage').append("Error: there was an error");
        $('#errorApproveModal').modal({
            keyboard: true
        });

        return false

    }
    console.log(isOk);
    **//both those checks are not working for some reason.**
    //
    if(isOk.status == 200 || isOk.statusText == "OK"){
        console.log('in is ok');
        this.remove();
    }

    return false;
}

顺便说一下:

App.Views.User = Backbone.View.extend({
      model: App.Models.User
      ,
      save: function...
});

有人可以帮忙吗? 有没有比这种方法更好的方法来处理成功和错误? 谢谢!! 罗伊

2 个答案:

答案 0 :(得分:0)

我不确定这是否是正确的方法,但我总是从视图的函数声明一个引用this的变量,然后成功使用它。像这样:

save: function(e) {

    // ADD THIS LINE
    var me = this;

    var isOk = this.model.save(null,
        {

    ....
            success: function(model, response){
                // USE me IN HERE
                me.render(); // e.g

            },
    ....
}

答案 1 :(得分:0)

你也可以这样做:

保存:功能(e){

var isOk = this.model.save(null,
    {

....
        success: function(model, response,options){
            // USE me IN HERE
            this.options.me.render(); // e.g

        },
        //ADD me this 
        me : this
....
}

使用这些选项,您可以执行所有参数。