Debian Codegraph @

README.md

raw symbols SCIP
1 # Cocktail [![npm](http://img.shields.io/npm/v/backbone.cocktail.svg)](https://npmjs.org/package/backbone.cocktail) [![npm](http://img.shields.io/npm/dm/backbone.cocktail.svg)](https://npmjs.org/package/backbone.cocktail)
2
3
4 Break out your shared [Backbone.js](http://backbonejs.org) model/collection/view behaviors into separate modules and mix them into your classes with Cocktail - an implementation of Backbone mixins.
5
6 * `bower install cocktail`
7 * `npm install backbone.cocktail`
8
9 ## Concocting Mixins
10
11 Mixins are simply bare-bones JavaScript objects that provide additional functionality to your Backbone objects. Think of them as bags of methods that will get added to all instances of your objects.
12
13 Here's an example mixin that implements selectability on a view based on a model's selection state:
14
15 window.MyMixins = {};
16
17 MyMixins.SelectMixin = {
18 initialize: function() {
19 this.model.on('change:selected', this.refreshSelect, this);
20 },
21
22 events: {
23 click: 'toggleSelect'
24 },
25
26 render: function() {
27 this.refreshSelect();
28 },
29
30 refreshSelect: function() {
31 this.$el.toggleClass('selected', this.model.get('selected'));
32 },
33
34 toggleSelect: function() {
35 this.model.set('selected', !this.model.get('selected'));
36 }
37 }
38
39 As you can see: nothing special, just a bag of functions.
40
41 > Obviously, the bit about `window.MyMixins` is just a suggested pattern for organizing your mixins!
42
43 > And, yes, having models know about view state like selection is often an anti-pattern... but it makes for a simple intelligible example!
44
45 ## Mixing Mixins In
46
47 Once you have your mixins defined including them in your Backbone object definitions is a one-liner:
48
49 var MyView = Backbone.View.extend({
50 events: {
51 'click .myChild': 'myCustomHandler'
52 }
53
54 initialize: function() {
55 ...
56 },
57
58 render: function() {
59 ...
60 },
61
62 etc...
63 });
64
65 Cocktail.mixin(MyView, MyMixins.SelectMixin, MyMixins.SomeOtherMixin);
66
67 Now all instances of `MyView` will have the selection behavior defined in the `SelectMixin`:
68
69 var view = new MyView(...);
70 view.toggleSelect(); //works!
71
72
73 **Alternatively**, you can lazily mix into your views/models like so:
74
75 var MyView = Backbone.View.extend({
76 events: {
77 'click .myChild': 'myCustomHandler'
78 }
79
80 initialize: function() {
81 Cocktail.mixin(this, MyMixins.SelectMixin, MyMixins.SomeOtherMixin);
82 },
83
84 render: function() {
85 ...
86 },
87
88 etc...
89 });
90
91 This looks a bit cleaner if you can't monkeypatch (described below). In addition, this syntax gives you the flexibility
92 to mix in certain methods in particular states of your application. For example, maybe you have an interface that you'd like
93 an object to assume on login/logout or in the presence of another object (like a Flash embed).
94
95 ### If you don't mind monkeypatching
96
97 By default, as of 0.2.0 Cocktail no longer messes with Backbone's built-in extend method. However, if you don't mind some monkey patching then running:
98
99 Cocktail.patch(Backbone);
100
101 *before* you define any classes will allow you to mixin code like this:
102
103 var MyView = Backbone.View.extend({
104 mixins: [MyMixins.SelectMixin, MyMixins.SomeOtherMixin],
105
106 etc...
107 });
108
109 or like this for CoffeeScript users:
110
111 class MyView extends Backbone.View
112 @mixin MyMixins.SelectMixin
113
114
115 with the monkey-patch installed, mixins are just a convenient bit of configuration at the top of your class definitions. Note that the patch should only be applied once.
116
117 ### Named mixins
118
119 Whether or not you're monkey patching Backbone, you can also use named mixins by registering them with Cocktail:
120
121 Cocktail.mixins = {
122 select: MyMixins.SelectMixin,
123 other: MyMixins.SomeOtherMixin
124 };
125
126 // Without monkey patching
127 Cocktail.mixin(MyView, 'select', 'other', MyMixins.yetAnotherMixin);
128
129 // With monkey patching
130 var MyView = Backbone.View.extend({
131 mixins: ['select', 'other', MyMixins.yetAnotherMixin],
132
133 etc...
134 });
135
136 ## But What About Collisions?
137
138 In the example above, both `MyView` and `SelectMixin` both defined `initialize`, and `render`. What happens with these colliding methods?
139
140 Cocktail automatically ensures that methods defined in your mixins do not obliterate the corresponding methods in your classes.
141 This is accomplished by wrapping all colliding methods into a new method that is then assigned to the final composite object.
142
143 Note: Cocktail will ensure that if you accidentally try to mix in the same method, it will not result in a collision and will do nothing.
144
145 ### How are colliding functions called?
146
147 Let's take a concrete example. Class **X** implements `render` and mixes in mixins **A**, **B**, and **C** (in that order). Of these only **A** and **C** implement `render`.
148
149 When `render` is called on instances of **X** the implementation of `render` in **X** is called first, followed by the implementation in **A** and then **C**. In this way the original implementation is always called first, followed by the mixins.
150
151 ### What are the return values from colliding functions?
152
153 The return value of the composite function is the **last** non-`undefined` return value from the chain of colliding functions.
154
155 To be clear: let's say **X** mixes in **A** and **B**. Say **X** implements a method `foo` that returns `bar`, **A** implements `foo` but returns nothing (i.e. `undefined` is implicitly returned) and **B** returns `baz`. Then instances of **X** will return `baz` -- the last non-`undefined` return value from `foo`'s **X** → **A** → **B** collision chain.
156
157 ## And how about hashes?
158
159 When both a mixin and the class define a hash, Cocktail will merge the hashes together. In the case of a key collision, keys and values defined in the hash on the class take precedence followed the hash on the first mixin, then the second mixin, etc...
160
161 Note that this includes the events hash. As a result, mixins are allowed to add new event listeners.
162
163 ## And what about subclasses?
164
165 Subclass hierarchies with mixins should work just fine. If a super class mixes in a mixin, then all subclasses will inherit that mixin. If those subclasses mixin additional mixins, those mixins will be folded in to the subclasses and collisions will be handled correctly, even collisions with methods further up the class hierarchy.
166
167 However, if a subclass redefines a method that is provided by a mixin of the super class, the mixin's implementation will *not* be called. This shouldn't be surprising: the subclass's method is further up in the prototype chain and is the method that gets evaluated. In this circumstance, you *must* remember to call `SubClass.__super__.theMethod.apply(this)` to ensure that the mixin's method gets called.
168
169 ## Testing Mixins
170
171 The [example](https://github.com/onsi/cocktail/tree/master/example) directory includes an example mixin and its usage, and the accompanying [Jasmine](http://www.github.com/pivotal/jasmine) test. It also includes a [readme](https://github.com/onsi/cocktail/tree/master/example) that walks through the testing pattern employed for testing mixins with Jasmine.
172
173 ## Dependencies, Installation, and Contributing
174
175 Cocktail requires:
176
177 - [Backbone](http://backbonejs.org) (duh) (tested with 1.1.0)
178 - [Underscore](http://underscorejs.org) (tested with 1.5.1)
179
180 Running Tests:
181
182 Open up `spec/SpecRunner.html` in your favorite browser.
183
184 Contributing:
185
186 You can contribute a new build by issuing the terminal command `grunt` within the root folder.
187
188
189 Future changes to backbone could break Cocktail or obviate its need.
190 If the latter happens - great! If the former: let me know and I'll try to
191 ensure compatibility going forward.
192
193 ## If you like Cocktail...
194 ...check out [Coccyx](http://github.com/onsi/coccyx). Coccyx helps you plug up backbone leaks with two things: named constructors and tear-downable view hierarchies.