Skip to content

Instantly share code, notes, and snippets.

@evangoer
Created September 29, 2011 05:37
Show Gist options
  • Save evangoer/1250052 to your computer and use it in GitHub Desktop.
Save evangoer/1250052 to your computer and use it in GitHub Desktop.
A more sugary way to create Y.Base derived objects.
/* What do we really care about when creating a Base-derived object?
1. the object we are deriving from
2. string name
3. properties and methods
4. attributes
Goals: simpler method with fewer args & less nesting. Simplify
adding attributes. No need for empty [] hack as with Y.Base.create() */
Y.Example = Y.Model.derive('example-model', {
// prototype methods and properties here
hello: function () {
return 'hi';
}
}, {
// attributes here
frobozz: {
value: 'zorkmid',
readOnly: true
},
grue: 17 // MOAR sugar; equivalent to grue: { value: 17 }
}, {
// publish events here
'somethingSpecial': {
emitFacade: true,
broadcast: 2,
}
});
/* NOTES:
1. Y.Base.derive() extends from Y.Base. Y.Model.derive() extends from
Y.Model. And so on. Eliminate an unnecessary arg.
2. Assumption: mixins are less important and developers can always do this
themselves. Perhaps allow a fourth optional [] argument to make it easier.
3. Assumption: adding statics like HTML_PARSER is easy. Developers can do
this themselves. Better to focus on making attributes less clumsy to add. */
@lsmith
Copy link

lsmith commented Oct 12, 2011

Right now there are generic extension methods on Y, then Y.Base.create(). We use the latter because it can do more, but it's an odd place for something used generically.

The generic derive method and the attribute/proto/events methods all suffer the same trap, where a user won't know if a given class has those static methods or not. This may not be too much of an issue given they're intended for the component/plugin author rather than the page implementer. With that in mind, having a derive method on the class is nice.

var SubClass = SuperClass.extend()
// I'm sure there are better names/method breakouts. This doesn't gracefully handle prototype properties.
.addMethods({ ... })
.mixin([ class extensions ])
.addAttributes({ ... })
.addEvents({ ... });

@evangoer
Copy link
Author

Well, I think I do like the chained methods approach as sugar for adding attributes and events. And for mixing in extensions. That approach seems cleaner to me than a single method that takes a whole bunch of arguments in a particular order.

Adding prototype methods through a special method seems weird to me, now that I'm looking at it.

@lsmith
Copy link

lsmith commented Oct 13, 2011

I completely agree. I didn't like the proto as a method.

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