gpt4 book ai didi

javascript - Backbone 实体

转载 作者:行者123 更新时间:2023-11-29 18:10:36 33 4
gpt4 key购买 nike

我是 backbone 的新手。但是当我研究模型实体时,我不明白一些事情。如果我们可以像 java 或 C# 这样的标准语言一样定义模型属性,那就太好了。有没有可能是这样的。所以我的想法是这样的:

MyEntity = Backbone.Model.extend({
// define class property here
defaults: {
name: null,
surname: null
}
});

var entity = new MyEntity();

//My Idea:
name = entity.get('name'); // return null
test = entity.get('test'); // this should throw exception, because test property does not exist
exist = entity.has('name'); // should return true. Property exist, but is empty
entity.set('test2', 'hello'); // this should threw exception, property test2 does not exist

// Reality:
name = entity.get('name'); // return null
test = entity.get('test'); // return undefined
exist = entity.has('name'); // return false
entity.set('test2', 'hello'); // ok, valid

那么是否可以修改 Backbone 模型使其像这样工作?非常感谢

最佳答案

您可以设置自己的自定义 getter 和 setter。

var MyEntity = Backbone.Model.extend({
defaults: {
name: null,
surname: null
},

customHas: function (key) {
return this.attributes.hasOwnProperty(key);
},

customGet: function (key) {
if (this.customHas(key)) {
return this.get(key);

} else {
throw('property does not exist');
}
},

customSet: function (key, val) {
if (this.customHas(key)) {
this.set(key, val);

} else {
throw('property does not exist');
}
}
});

See this example fiddle .

关于javascript - Backbone 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27693395/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com