Last active
August 29, 2015 14:13
-
-
Save outdooricon/25419aff40cb6e4c5aa9 to your computer and use it in GitHub Desktop.
Easily use composition to build Backbone object prototypes
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
| extendPrototypeFromArray = (protoConstructor) -> | |
| _.wrap protoConstructor.extend, (cachedExtend, mixinArray, prototype) -> | |
| if mixinArray instanceof Array | |
| # Uses _.defaults so base object overrides anything being added | |
| fullProto = _.defaults.apply _, [prototype].concat(mixinArray) | |
| else | |
| fullProto = mixinArray | |
| cachedExtend.call @, fullProto | |
| Backbone.Model.extend = extendPrototypeFromArray Backbone.Model | |
| Backbone.Collection.extend = extendPrototypeFromArray Backbone.Collection | |
| Backbone.Router.extend = extendPrototypeFromArray Backbone.Router | |
| Backbone.View.extend = extendPrototypeFromArray Backbone.View |
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
| NewView = Backbone.Model.extend [ViewLogging, ViewSyncing], | |
| el: '.view' | |
| events: | |
| 'click .title': 'logIt' | |
| 'click .a': 'setA' | |
| # This will produce the equivalent to: | |
| # NewView = Backbone.Model.extend | |
| # el: '.view' | |
| # | |
| # events: | |
| # 'click .title': 'logIt' | |
| # 'click .a': 'setA' | |
| # | |
| # logIt: -> | |
| # console.log 'logged it' | |
| # | |
| # setA: -> | |
| # @model.set | |
| # a: 'a' | |
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
| ViewLogging = | |
| logIt: -> | |
| console.log 'logged it' |
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
| ViewSyncing = | |
| setA: -> | |
| @model.set | |
| a: 'a' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment