Module: Glimmer::DataBinding::ObservableHashable

Includes:
Observable
Included in:
ObservableHash, ObservableModel
Defined in:
lib/glimmer/data_binding/observable_hashable.rb

Overview

Represents a Hash-like object with attributes writable via :[]= store method like Hash, Struct, and OpenStruct Expects including class to have the following methods:

  • key_observer_list

  • all_key_observer_list

  • unregister_dependent_observer

  • ensure_array_object_observer

Constant Summary collapse

OBSERVED_STORE_METHOD =
lambda do |options|
  lambda do |key, value|
    if key_observer_list(key).empty?
      if all_key_observer_list.empty?
        self.send('__original__store', key, value)
      else
        old_value = self[key]
        unregister_dependent_observers(nil, old_value) # remove dependent observers previously installed in ensure_array_object_observer
        self.send('__original__store', key, value)
        notify_observers(key)
        ensure_array_object_observer(nil, value, old_value, options)
      end
    else
      old_value = self[key]
      unregister_dependent_observers(key, old_value) # remove dependent observers previously installed in ensure_array_object_observer
      self.send('__original__store', key, value)
      notify_observers(key)
      ensure_array_object_observer(key, value, old_value, options)
    end
  end
end

Instance Method Summary collapse

Methods included from Observable

#add_observer, #inspect, #remove_observer

Instance Method Details

#add_key_writer_observer(key = nil, options) ⇒ Object


57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/glimmer/data_binding/observable_hashable.rb', line 57

def add_key_writer_observer(key = nil, options)
  ensure_array_object_observer(key, self[key], nil, options)
  begin
    method('__original__store')
  rescue
    define_singleton_method('__original__store', store_method)
    define_singleton_method('[]=', &OBSERVED_STORE_METHOD.call(options))
  end
rescue => e
  #ignore writing if no key writer exists
  Glimmer::Config.logger.debug {"No need to observe store method: '[]='\n#{e.message}\n#{e.backtrace.join("\n")}"}
end

#store_methodObject


70
71
72
# File 'lib/glimmer/data_binding/observable_hashable.rb', line 70

def store_method
  self.class.instance_method('[]=') rescue self.method('[]=')
end