3f1df5a3 by Michael Richards

Implement a universal sync function to use when binding/unbinding. This removed …

…the need to define a wrapped callback for unsubscribing. [Closes #16]
1 parent e0b6c36b
......@@ -26,7 +26,7 @@ describe('Rivets.Binding', function() {
it('subscribes to the model for changes via the adapter', function() {
spyOn(rivets.config.adapter, 'subscribe');
binding.bind();
expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'name', binding.set);
expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'name', binding.sync);
});
describe('with preloadData set to true', function() {
......@@ -64,8 +64,8 @@ describe('Rivets.Binding', function() {
it('sets up observers on the dependant attributes', function() {
spyOn(rivets.config.adapter, 'subscribe');
binding.bind();
expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'fname', binding.dependencyCallbacks['fname']);
expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'lname', binding.dependencyCallbacks['lname']);
expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'fname', binding.sync);
expect(rivets.config.adapter.subscribe).toHaveBeenCalledWith(model, 'lname', binding.sync);
});
});
});
......
......@@ -56,29 +56,26 @@ class Rivets.Binding
else
@routine @el, value
# Syncs up the view binding with the model.
sync: =>
@set if @options.bypass
@model[@keypath]
else
Rivets.config.adapter.read @model, @keypath
# Subscribes to the model for changes at the specified keypath. Bi-directional
# routines will also listen for changes on the element to propagate them back
# to the model.
bind: =>
if @options.bypass
@set @model[@keypath]
@sync()
else
Rivets.config.adapter.subscribe @model, @keypath, @set
if Rivets.config.preloadData
@set Rivets.config.adapter.read @model, @keypath
Rivets.config.adapter.subscribe @model, @keypath, @sync
@sync() if Rivets.config.preloadData
if @options.dependencies?.length
@dependencyCallbacks = {}
for keypath in @options.dependencies
callback = @dependencyCallbacks[keypath] = (value) =>
@set if @options.bypass
@model[@keypath]
else
Rivets.config.adapter.read @model, @keypath
Rivets.config.adapter.subscribe @model, keypath, callback
Rivets.config.adapter.subscribe @model, keypath, @sync
if @type in @bidirectionals
bindEvent @el, 'change', @publish
......@@ -91,12 +88,11 @@ class Rivets.Binding
# Unsubscribes from the model and the element.
unbind: =>
unless @options.bypass
Rivets.config.adapter.unsubscribe @model, @keypath, @set
Rivets.config.adapter.unsubscribe @model, @keypath, @sync
if @options.dependencies?.length
for keypath in @options.dependencies
callback = @dependencyCallbacks[keypath]
Rivets.config.adapter.unsubscribe @model, keypath, callback
Rivets.config.adapter.unsubscribe @model, keypath, @sync
if @type in @bidirectionals
@el.removeEventListener 'change', @publish
......