serpentem/theoricus — pull request #51 by giuliandrimba (2013-06-09 21:36:05+00:00)
Title: Fixed model getter and setter

## __Problem:__

The getter and setter implementations was not working.

See issue [#47](https://github.com/serpentem/theoricus/issues/47)

## __Why not?__

Lets examine this simple example:

``` coffeescript

class Model
@define_title = ->

_val = null

@getter = -> _val
@setter = (value) ->
console.log "set"
_val = value

Object.defineProperty @::, "title", get:@getter, set:@setter

class Todo extends Model

@define_title()

a = new Todo
a.title = "I am A"

b = new Todo
b.title = "I am B"

console.log a.title #Returns 'I am B'
```
Run this [example](http://jsfiddle.net/giuliandrimba/wnfrw/1/) at JSFIddle.

__What is happening here?__

+ The `define_title` method is called one time, using the local variable `_val`
+ But, for each time I set the variable for an instance, it overrides the local variable `_val`, changing all the instances properties value.

## __Solution:__

Create a local variable for each class function:

``` coffeescript

class Model
@define_title = ->

@_title = null

@getter = -> @_title
@setter = (value) ->
console.log "set"
@_title = value

Object.defineProperty @::, "title", get:@getter, set:@setter

class Todo extends Model

@define_title()

a = new Todo
a.title = "I am A"

b = new Todo
b.title = "I am B"

console.log a.title #Returns 'I am A'
```
Run this [example](http://jsfiddle.net/giuliandrimba/wnfrw/2/) at JSFIddle.

__Downsides:__

With this approach, the variable is not local anymore, exposed in the Class function (not instance). Eg:

``` coffeescript
console.log a #Todo {_title: "I am A", constructor: function}
```