【问题标题】:Javascript/typescript property decorator that mimics @NSManaged模仿 @NSManaged 的​​ Javascript/typescript 属性装饰器
【发布时间】:2018-04-05 16:08:54
【问题描述】:

我一直在尝试使用 Swift/Parse,现在想将我的代码转换为 React / ReactNative / Parse-React 看看是否可以这样做。

在 Swift 中,可以扩展 PFObject 并将 @NSManaged 应用于属性以处理设置 Parse 的托管属性。

open class FooModel: PFObject, PFSubclassing {
    open class func parseClassName() -> String {
        return "FooModel"
    }
    @NSManaged open var name: String
}

我尝试对以下 Javascript 装饰器执行相同的操作,但它似乎没有按预期工作。正在调用装饰器并调用相应的“set(key, val)”,但该值未保存到我的 Parse 服务器。

这甚至可能吗?我错过了什么吗?

谢谢

var Parse = require('parse/react-native');

// function NSManaged(target, property, descriptor) {
function NSManaged<T>(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<T>) {
    return {
        set: function (value) {
            if ( target instanceof Parse.Object ) {
                target.set( propertyKey, value, {
                    error: function(obj, error) {
                        console.log( 'the set failed: ' + error);
                        }
                    });
                console.log('target: ' + target.constructor.name + ' property: ' + propertyKey + ' value: ' + value);
            } else {
                console.log( 'target is not an instanceof Parse.Object');
            }
        },
        get: function() {
            let val = target.get( propertyKey);
            console.log('get', val);
            return val;
        },
        enumerable: true,
        configurable: true
    };
  };

export class FooModel extends Parse.Object {
    @NSManaged
    name?: string

    constructor() {
        // @ts-ignore
        super('FooModel');
    }

}


let foo = new FooModel();
foo.name = "test";
foo.set( "name2", "test" );
foo.save();

【问题讨论】:

  • 我现在无法测试,但是您的代码包含一个明显的错误,您将值设置为targettarget 是类,而不是类的实例。您应该在 set/get 函数中使用 this 来访问实例。
  • @TitianCernicova-Dragomir 谢谢!

标签: javascript typescript parse-platform decorator


【解决方案1】:

根据 Titian 的回复,我将代码更改为以下内容,这似乎符合我的预期。 'name' 和 'name2' 正在保存到我的 Parse Server。

function NSManaged<T>(target: any, propertyKey: string, descriptor: TypedPropertyDescriptor<T>) {
    return {
        set: function (value) {
            if ( target instanceof Parse.Object ) {
                this.set( propertyKey, value, {
                    error: function(obj, error) {
                        console.log( 'the set failed: ' + error);
                        }
                    });
            } else {
                console.log( 'target is not an instanceof Parse.Object');
            }
        },
        get: function() {
            let val = this.get( propertyKey);
            console.log('get', val);
            return val;
        },
        enumerable: true,
        configurable: true
    };
  };

【讨论】:

    猜你喜欢
    • 2019-07-29
    • 2018-07-20
    • 2020-06-20
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    • 2021-05-17
    相关资源
    最近更新 更多