Backbone和TypeScript,一段不愉快的婚姻:构建一个类型安全的“获取”?

问题描述 投票:12回答:4

我正在尝试将TypeScript与Backbone.js一起使用。它“有效”,但Backbone的get()和set()失去了很多类型的安全性。我正在尝试编写一个可以恢复类型安全的辅助方法。像这样的东西:

我把它放在我的模型中:

object() : IMyModel  {
    return attributes; // except I should use get(), not attributes, per documentation
}

这在消费者中:var myVar = this.model.object().MyProperty;

使用这种语法,我得到了TypeScript的知识,MyProperty存在并且是bool,这很棒。但是,backbone.js docs告诉我使用get和set而不是直接使用属性hash。那么有没有任何神奇的Javascript方法通过get和set正确管道该对象的使用?

javascript backbone.js typescript
4个回答
17
投票

我们正在大量使用TypeScript主干,并提出了一种新颖的解决方案。 请考虑以下代码:

interface IListItem {
    Id: number;
    Name: string;
    Description: string;
}

class ListItem extends Backbone.Model implements IListItem {
    get Id(): number {
        return this.get('Id');
    }
    set Id(value: number) {
        this.set('Id', value);
    }
    set Name(value: string) {
        this.set('Name', value);
    }
    get Name(): string {
        return this.get('Name');
    }
    set Description(value: string) {
        this.set('Description', value);
    }
    get Description(): string {
        return this.get('Description');
    }

    constructor(input: IListItem) {
        super();
        for (var key in input) {
            if (key) {
                //this.set(key, input[key]);
                this[key] = input[key];
            }
        }
    }
}

请注意,接口定义了模型的属性,构造函数确保传递的任何对象都具有Id,Name和Description属性。 for语句只调用每个属性的骨干集。这样以下测试将通过:

describe("SampleApp : tests : models : ListItem_tests.ts ", () => {
    it("can construct a ListItem model", () => {
        var listItem = new ListItem(
            {
                Id: 1,
                Name: "TestName",
                Description: "TestDescription"
            });
        expect(listItem.get("Id")).toEqual(1);
        expect(listItem.get("Name")).toEqual("TestName");
        expect(listItem.get("Description")).toEqual("TestDescription");

        expect(listItem.Id).toEqual(1);

        listItem.Id = 5;
        expect(listItem.get("Id")).toEqual(5);

        listItem.set("Id", 20);
        expect(listItem.Id).toEqual(20);
    });
});

更新:我已更新代码库以使用ES5 get和set语法,以及构造函数。基本上,您可以使用Backbone .get和.set作为内部变量。


10
投票

我提出了以下使用泛型和ES5 getter / setter,建立了/u/blorkfish的答案。

class TypedModel<t> extends Backbone.Model {
    constructor(attributes?: t, options?: any) {
        super(attributes, options);

        var defaults = this.defaults();
        for (var key in defaults) {
            var value = defaults[key];

            ((k: any) => {
                Object.defineProperty(this, k, {
                    get: (): typeof value => {
                        return this.get(k);
                    },
                    set: (value: any) => {
                        this.set(k, value);
                    },
                    enumerable: true,
                    configurable: true
                });
            })(key);
        }
    }

    public defaults(): t {
        throw new Error('You must implement this');
        return <t>{};
    }
}

注意:Backbone.Model默认是可选的,但由于我们使用它来构建getter和setter,现在它是必需的。抛出的错误会强制您执行此操作。也许我们可以想出更好的方法?

并使用它:

interface IFoo {
    name: string;
    bar?: number;
}

class FooModel extends TypedModel<IFoo> implements IFoo {
    public name: string;
    public bar: number;

    public defaults(): IFoo {
        return {
            name: null,
            bar: null
        };
    }
}

var m = new FooModel();
m.name = 'Chris';
m.get('name'); // Chris
m.set({name: 'Ben', bar: 12});
m.bar; // 12
m.name; // Ben

var m2 = new FooModel({name: 'Calvin'});
m2.name; // Calvin

它比理想的更冗长,它要求你使用默认值,但效果很好。


0
投票

这是一种使用装饰器的方法,创建一个这样的基类:

export class Model<TProps extends {}> extends Backbone.Model {

    static Property(fieldName: string) {
        return (target, member, descriptor) => {
            descriptor.get = function() {
                return this.get(fieldName);
            };
            descriptor.set = function(value) {
                this.set(fieldName, value);
            };
        };
    }

    attributes: TProps;
}

然后像这样创建自己的类:

class User extends Model<{id: string, email: string}> {
    @Model.Property('id')        set Id(): string { return null; }
    @Model.Property('email')     set Email(): string { return null; }
}

并使用它:

var user = new User;
user.Email = '[email protected]';
console.log(user.Email);

0
投票

我正在努力解决同样的问题,但我想我用TypeScript聊天组找到了有趣的解决方案。解决方案似乎很有希望,我想在这里分享。所以我的代码现在看起来像这样

//Define model structure
interface IMarkerStyle{
    Shape:string;
    Fill:string;
    Icon:string;
    Stroke:string;
};

export class MarkerStyle extends StrongModel<IMarkerStyle>{  
//Usage
let style=new MarkerStyle();

//Most interesting part. Oddly enough thease lines check for type
style.s("Fill","#F00"); //setter OK:  Fill is defined as string
style.s("Fill",12.3);   //setter ERROR: because of type mismatch

我得到的另一个好处是它检查默认值和构造函数参数以便与接口兼容。因此,静态类型检查不允许您为不存在的属性指定默认值

let style=new MarkerStyle(
  {
    Shape:"circle", //OK 
    Phill:"#F00",   //ERROR typo in field name
    Icon:"car"      //OK
                    //ERROR Stroke is not optional in interface and not specified here
  }
);

© www.soinside.com 2019 - 2024. All rights reserved.