I'm new in backbone. But when i study model entity I don't understand a few things. It would be great if we can define model property as in standard language like java or C#. Is it possible something like that. So my idea look like this:
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
So is it possible to modify backbone model to work like this? Thanks a lot
You can set up your own custom getters and setters.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With