Skip to content

Instantly share code, notes, and snippets.

@naganowl
Created June 20, 2014 00:24
Show Gist options
  • Save naganowl/7cf53508ecb46c3a1558 to your computer and use it in GitHub Desktop.
Save naganowl/7cf53508ecb46c3a1558 to your computer and use it in GitHub Desktop.
Compare and contrast the different strategies of mixing in objects

Forgive the sloppy code and structure, I just needed some scaffolding to explain the issue at hand. Assume RequireJS is used for modules.

The way this is implemented now, mixin will have it's internal variables set to 'privateStuff' rather than 'private', so when the user navigates to the single action, it won't alert private.

This is because of how the items are retrieved in the order they are specified and because the closure scope in the mixin is shared between all instances that use it, but preserve essentially the last variable that it was called with.

The problem can be mitigated if the mixins are mixed on initialize of the models or if the exports of mixin curries the methods which use the private properties, so that the variable is bound to the specified option.

define (require, exports) ->
Chaplin = require 'chaplin'
SingleView = require 'single-view'
OtherView = require 'other-view'
SingleModel = require 'single-model'
OtherModel = require 'other-model'
exports = class Controller extends Chaplin.Controller
single: ->
model = new SingleModel()
new SingleView {model}
other: ->
model = new OtherModel()
new OtherView {model}
define (require, exports) ->
privateStuff = ''
privateFunc = ->
alert privateStuff
exports = (opts={}) ->
privateStuff = opts.privateStuff or 'private'
@privateFunc = privateFunc
this
define (require, exports) ->
Chaplin = require 'chaplin'
mixin = require 'mixin'
exports = class OtherModel extends Chaplin.Model
mixin.call @prototype, {'privateStuff'}
define (require, exports) ->
Chaplin = require 'chaplin'
exports = class OtherView extends Chaplin.View
render: -> @model.privateFunc()
define (require, exports) ->
Chaplin = require 'chaplin'
mixin = require 'mixin'
exports = class SingleModel extends Chaplin.Model
mixin.call @prototype
define (require, exports) ->
Chaplin = require 'chaplin'
exports = class SingleView extends Chaplin.View
render: -> @model.privateFunc()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment