0

我正在尝试保存模型并在成功时取消渲染它:问题是在成功中我无法引用 this 引用(即视图),我也无法引用 this.model 的变量 isOk.status。 save(...) 返回。编码:

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...
});

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

4

2 回答 2

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

            },
    ....
}
于 2013-04-11T17:03:16.533 回答
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
....
}

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

于 2013-04-20T19:21:20.507 回答