2

给定以下 JS,如何设置对象的message属性PlateCheck

var plateCheck = {
        plateNumber: '',
        message: '',
        alertClass: '',
        checkPlate: function (plateNumber) {
            PlateCheckService.checkPlate(plateNumber).then(function (response) {
                var data = response.data;

                if (data.VehicleAtl !== null) {
                    this.message = "Hot!";
                    this.alertClass = 'alert-danger';
                } else {
                    this.message = "Plate #" + data.PlateNumber + " is clean.";
                    this.alertClass = 'alert-success';
                }
            });
        }
    };

编辑

PlateCheckService.checkPlate(plateNumber)返回一个承诺...

4

1 回答 1

3

这可能只是一个范围问题,但通过调用返回相同的对象plateCheck.checkPlate(fooPlateNumber)也许这会奏效。

var plateCheck = {
        plateNumber: '',
        message: '',
        alertClass: '',
        checkPlate: function (plateNumber) {
            var me = this;
            PlateCheckService.checkPlate(plateNumber).then(function (response) {
                var data = response.data;
                me.plateNumber = plateNumber;
                if (data.VehicleAtl !== null) {
                    me.message = "Hot!";
                    me.alertClass = 'alert-danger';
                } else {
                    me.message = "Plate #" + data.PlateNumber + " is clean.";
                    me.alertClass = 'alert-success';
                }
            });
        }
    };

但也许你可以提取服务函数,返回一个plateCheck对象。

function checkPlate(plateNumber) {
    var plateCheck = {};
    plateCheck.plateNumber = plateNumber;
    PlateCheckService.checkPlate(plateNumber).then(function (response) {
        var data = response.data;
        if (data.VehicleAtl !== null) {
            plateCheck.message = "Hot!";
            plateCheck.alertClass = 'alert-danger';
        } else {
            plateCheck.message = "Plate #" + data.PlateNumber + " is clean.";
            plateCheck.alertClass = 'alert-success';
        }
    });
    return plateCheck;
}
于 2013-10-27T20:30:07.447 回答