Skip to content

Instantly share code, notes, and snippets.

@gazs
Created April 25, 2011 20:48
Show Gist options
  • Select an option

  • Save gazs/941187 to your computer and use it in GitHub Desktop.

Select an option

Save gazs/941187 to your computer and use it in GitHub Desktop.
class Cell extends Backbone.Model
initialize: ->
@__defineGetter__ 'selected', -> @get 'selected'
@__defineSetter__ 'selected', (value)-> @set selected:value
class Sheet extends Backbone.Collection
initialize: ->
@__defineGetter__ 'size', -> Math.sqrt @length
model: Cell
every_nth: (n, offset=0, smallest=0, largest=@length) ->
@select (cell) =>
(@indexOf cell) % n == offset && (@indexOf cell) >=smallest && (@indexOf cell) <= largest
check_match: (cells) ->
_.pluck(cells, 'selected').reduce (p,c) -> p && c
row_matches: ->
results = for row in [0...@size]
start = row*@size
@check_match @models.slice(start, start + @size)
_.reduce results, (p,c) -> p || c
column_matches: ->
results = for row in [0...@size]
@check_match @every_nth @size, row
_.reduce results, (p,c) -> p || c
diagonal_matches: ->
results = [
@check_match @every_nth @size+1
@check_match @every_nth @size-1, 0, @size-1, @length-@size
]
_.reduce results, (p,c) -> p || c
window.sheet = new Sheet
sheet.refresh [
{ value: 'foo', selected: true }
{ value: 'bar', selected: true }
{ value: 'baz', selected: true }
{ value: 'bla', selected: true }
{ value: 'foo', selected: true }
{ value: 'foo', selected: true }
{ value: 'foo', selected: true }
{ value: 'bar', selected: true }
{ value: 'baz', selected: true }
{ value: 'bla', selected: true }
{ value: 'bar', selected: true }
{ value: 'baz', selected: false }
{ value: 'bla', selected: false }
{ value: 'bar', selected: true }
{ value: 'baz', selected: false }
{ value: 'bla', selected: false }
]
@gazs
Copy link
Author

gazs commented Apr 26, 2011

Thanks, I'll try this tomorrow. No, this is some Backbone-related stuff: you write an initialize function that gets added to the constructor function that Backbone will create for you, otherwise they will cancel each other out

@gazs
Copy link
Author

gazs commented Apr 26, 2011

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