我有一个使用Alloy模型创建的Titanium / Appcelerator应用程序,它使用Backbone.js。每个模型都有一个文本字段,我想将其解释为数字。到目前为止,每次我需要使用它时,我都会使用parseInt()
来获取属性并进行转换。
有没有办法在每次访问时自动将该属性解释为数字?也许是某种自动转换?我想避免更改数据库中字段的类型,并且必须进行某种迁移。
这是我的模型的精简示例。属性date
以字符串形式保存到数据库中。但由于它是UTC时间戳,我希望始终将其解释为数字。
exports.definition = {
config: {
columns: {
"name": "text",
"date": "text"
},
adapter: {
type: "sql",
collection_name: "people"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
// extended functions and properties go
});
return Collection;
}
};
答案 0 :(得分:2)
您可以像这样扩展您的模型:
exports.definition = {
config: {
columns: {
"name": "text",
"date": "text"
},
adapter: {
type: "sql",
collection_name: "people"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
transform: function transform() {
var transformed = this.toJSON();
transformed.date = parseInt(transformed.date);
return transformed;
}
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
// extended functions and properties go
});
return Collection;
}
};
或强>
您可以在UI元素上使用 dataTransform read here 属性来应用转换方法。
<强> view.xml用强>
<Alloy>
<Collection src="your_collection_name" />
<Window class="container">
<TableView dataCollection="your_collection_name" dataTransform="transformFunction">
</TableView>
</Window>
</Alloy>
<强> view.js 强>
function transformFunction(model) {
var transformed = this.toJSON();
transformed.date = parseInt(transformed.date);
return transformed;
}
这是您可以使用转换方法修改属性的方法,或者您也可以将任何自定义属性添加到模型中并使用相同名称引用它。