Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

done with events

  • Loading branch information...
commit 2fc1774283e2637995b9b1e3f95f511e746cebd3 1 parent a727403
@dnagir authored
View
2  README.md
@@ -156,7 +156,7 @@ class @Page extends ko.Model
@configure 'page'
# Subscribe to 'sayHi' event
- on 'sayHi', (name) ->
+ @on 'sayHi', (name) ->
alert name + @name
page = Page.new name: 'Home'
View
22 lib/assets/javascripts/knockout/model.js.coffee
@@ -17,6 +17,26 @@ class Module
obj.extended?.apply(@)
@
+Events =
+ ClassMethods:
+ extended: -> @include Events.InstanceMethods
+ on: (eventName, callback) ->
+ @events ||= {}
+ @events[eventName] || = []
+ @events[eventName].push callback
+
+ InstanceMethods:
+ trigger: (eventName, args...) ->
+ events = @constructor.events
+ handlers = events[eventName] || []
+ callback.apply(this, args) for callback in handlers
+ this # so that we can chain
+
+Callbacks =
+ ClassMethods:
+ tbd: ->
+ InstanceMethods:
+ tbd: ->
Ajax =
ClassMethods:
@@ -70,6 +90,8 @@ Ajax =
class Model extends Module
@extend Ajax.ClassMethods
+ @extend Events.ClassMethods
+ @extend Callbacks.ClassMethods
constructor: (json) ->
me = this
View
25 spec/javascripts/knockout/model_spec.js.coffee
@@ -1,10 +1,13 @@
class Page extends ko.Model
@configure 'page'
+ @on 'sayHi', (hi) ->
+ @sayHi = hi
describe "Model", ->
beforeEach ->
+ jasmine.Ajax.useMock()
@page = new Page
id: 123
name: 'Home'
@@ -24,9 +27,6 @@ describe "Model", ->
expect(@page.persisted()).toBeFalsy()
describe "Ajax", ->
- beforeEach ->
- jasmine.Ajax.useMock()
-
it "should return jQuery deferred when saving", ->
expect( @page.save().done ).toBeTruthy()
@@ -56,6 +56,12 @@ describe "Model", ->
name: 'Home'
content: 'Hello'
+ it "should not save if invalid", ->
+ @page.errors.name = 'whatever'
+ expect(@page.save()).toBeFalsy()
+ mostRecentAjaxRequest().toBeFalsy()
+
+
describe "errors", ->
it "should have errors for fields", ->
e = @page.errors
@@ -83,3 +89,16 @@ describe "Model", ->
responseText: '{"name": ["got ya", "really"]}'
expect( @page.errors.name() ).toBe "got ya, really"
+ describe "events", ->
+ it "should raise events", ->
+ @page.trigger('sayHi', 'abc')
+ expect(@page.sayHi).toBe 'abc'
+
+ describe "callbacks", ->
+ it "beforeSave should be called ", -> expect('tbd').toBe 'done'
+ it "beforeValidation should be called", -> expect('tbd').toBe 'done'
+
+ describe "validations", ->
+ it "should execute the validator", -> expect('tbd').toBe 'done'
+ it "should revalidate when field changes", -> expect('tbd').toBe 'done'
+
Please sign in to comment.
Something went wrong with that request. Please try again.