骨干验证和回调

Backbone validation and callback

本文关键字:回调 验证      更新时间:2023-09-26

谁能帮助我,Javascript采取函数'检测'未定义,我们怎么能从回调返回值检测函数?

validate: function (attrs, options) {
    if (!this.detect(attrs.selectedFile, this.onComplete)) {
        return "this is an error message";
    }
},
detect: function (file, callback) {
    var attributes = this.attributes,
        image = new Image();
    image.onload = function () {
        if (condition_is_false_return_false) {
            callback(false);
        } else {
            callback(true);
        }
    };
    image.src = URL.createObjectURL(file);
},
onComplete: function (value) {
    return value;
}

代码中有两个问题。1. validate函数只验证attr候选者,这里的"this"对象有歧义,它可能不是模型。因此this.detect没有定义。你可能需要在下划线中使用bind函数

  • 从技术上讲,在设置属性之前运行validate函数。即使你能成功地调用detect函数,在它里面,当你这样做的时候。属性时,您将得到一个空集。所以你什么都探测不到。最好将这些函数设置为静态,这意味着它们不引用"this"
  • 我做了一个jsfiddle,

        var myOwnModel=Backbone.Model.extend({
        initialize:function(model,options){
        Backbone.Model.prototype.initialize.apply(this,arguments);
        },
        validate: function (attrs, options) {
            console.log("doing validate",attrs);
        if (!this.detect(attrs.selectedFile, this.onComplete)) {
            return "this is an error message";
        }
        },
        detect: function (file, callback) {
            var attributes = this.attributes,
                image = new Image();
                        console.log("running detect",attributes) // Here attributes does not have the new attr. 
            image.onload = function () {
                if (condition_is_false_return_false) {
                    callback(false);
                } else {
                    callback(true);
                }
            };
            image.src = URL.createObjectURL(file);
        },
        onComplete: function (value) {
            return value;
        }
    })
    var a=new myOwnModel({a:1})
    a.fetch();
    // or test it with 
    a.set({b:1},{validate:true});
    console.log(a)
    

    看起来验证确实有访问"this"的权限。并且检测功能成功运行。那么问题是什么呢?