Created
March 10, 2011 23:58
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' | |
} | |
} | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
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
You might want to use
this.reset( prop )
instead of setting things back to the static default values: https://gist.github.com/867093