Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Entity

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

like image 300
John Avatar asked Dec 11 '25 18:12

John


1 Answers

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.

like image 111
Adam Hart Avatar answered Dec 13 '25 07:12

Adam Hart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!