Skip to content

Instantly share code, notes, and snippets.

@kara-ryli
Created March 10, 2011 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save kara-ryli/865213 to your computer and use it in GitHub Desktop.
Save kara-ryli/865213 to your computer and use it in GitHub Desktop.
How to override individual properties of an Object-based attribute in YUI3 Base subclasses
var MyClass = Y.Base.create('my-class', Y.Base, [], {
_mergeProps: function (value, prop) {
var cur = this.get(prop);
if (Y.Lang.isUndefined(cur)) {
cur = this.constructor.ATTRS[prop].value;
}
return Y.Lang.isObject(value) ? Y.merge(cur, value) : Y.Attribute.INVALID_VALUE;
}
}, {
ATTRS: {
dict: {
value: {
foo: 'bar',
test: false
},
setter: '_mergeProps'
}
}
});
var instance = new MyClass({
dict: {
test: true
}
});
instance.get('dict'); // { foo: 'bar', test: true }
instance.set('dict', { thirdVal: 'yes' });
instance.get('dict'); // { foo: 'bar', test: true, thirdVal: 'yes' }
delete instance.get('dict').thirdVal;
instance.get('dict'); // { foo: 'bar', test: true }
@ericf
Copy link

ericf commented Mar 12, 2011

You might want to use this.reset( prop ) instead of setting things back to the static default values: https://gist.github.com/867093

@kara-ryli
Copy link
Author

Since the reset method sits within a validator, this.reset(prop) throws a too much recursion error.

Checking for undefined is important because when the class is initialized, the current value of the attr is undefined - hence why I go back to the static defaults. It does make sense to check that the new value is an object though, as setting the property to, e.g. a String will cause unexpected results.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment