我有几个 Backbone 模型:
var MainThing = Backbone.Model(/* some methods */);
var CustomerFacingThing = MainThing.extend(/* overrides of those methods */);
在我的代码中的几个地方,我有一个 MainThing
实例,但我想将其转换为 CustomerFacingThing
,以便我可以将其传递给我的客户的某些代码- 编写代码:
var mainThing = new MainThing();
customerFunction(mainThing.convertToCustomerFacingThing());
我的问题是,最好的方法是什么?我能想到的一种方法是改变原型(prototype):
mainThing.prototype = CustomerFacingThing.prototype;
但这不会改变“隐藏原型(prototype)”,所以我不确定这是否有效(例如,我不确定mainThing instanceof CustomerFacingThing
是否为true
).
我还可以将属性和事件复制到新的 CustomerFacingThing
实例:
var customerFacingVersion = new CustomerFacingThing();
customerFacingVersion.attributes = mainThing.attributes;
customerFacingVersion.events = mainThing.events;
但是由于此时事件已经绑定(bind),我不确定这是否有效。另外,mainThing
可能具有非属性属性,所以我确实必须这样做:
_(mainThing).each(function(value, key) {
customerFacingThing[key] = value;
});
但这会使用这些方法的主要版本覆盖实例上面向客户的方法。
那么,谁能解释一下更改 Backbone.Model 实例类的最佳方法吗?
最佳答案
我建议使用 CustomerFacingThing 构造函数 - 并将 MainThing 作为参数传递。
由于 Backbone.Models 将其数据存储在属性中,因此下面的代码应该是相同的:
var mainThing = new MainThing();
var customerThing = new CustomerThing();
mainThing.get('propertyName') == customerThing.get('propertyName');
然后您可以在构造函数中使用以下代码:
请注意,这是 TypeScript 语法。
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'); }
constructor(input: IListItem) {
super();
for (var key in input) {
if (key) {
this[key] = input[key];
}
}
}
}
可以在此处找到此技术的详细信息:http://blorkfish.wordpress.com/2013/03/20/typescript-strongly-typed-backbone-models/
关于javascript - Backbone : Best Way to Convert Model to Different Model Class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23795626/