Skip to content

Commit

Permalink
Add Access.on and Access.on_changed
Browse files Browse the repository at this point in the history
  • Loading branch information
seanchas116 committed May 16, 2015
1 parent c594e32 commit 5662e0c
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
33 changes: 32 additions & 1 deletion lib/qml/access.rb
Expand Up @@ -13,10 +13,29 @@ class PropertyInfo
# @api private
class SignalInfo
attr_accessor :params
attr_accessor :listeners

def initialize
@listeners = []
end
end

def initialize(*args, &block)
self.class.property_infos.each_value.map(&:initializer).compact.each(&:call)

self.class.property_infos.each do |name, info|
if info.initializer
self.__send__ :"#{name}=", instance_eval(&info.initializer)
end
end

self.class.signal_infos.each do |name, info|
__send__(name).connect do |*args|
info.listeners.each do |listener|
instance_eval(&listener)
end
end
end

super
end

Expand Down Expand Up @@ -108,6 +127,18 @@ def property_infos(include_super = true)
end
end

def on(signal, &block)
info = signal_infos(false)[signal.to_sym] or fail AccessError, "no signal `#{signal}` found"
info.listeners << block
block
end

def on_changed(property, &block)
on(:"#{property}_changed", &block)
end

private :on, :on_changed

# Registers the class as a QML type.
# @param opts [Hash]
# @option opts [String] :under the namespece which encapsulates the exported QML type. If not specified, automatically inferred from the module nesting of the class.
Expand Down
36 changes: 36 additions & 0 deletions spec/qml/access_spec.rb
Expand Up @@ -5,6 +5,42 @@
let(:component) { QML::Component.new data: data }
let(:root) { component.create }

describe 'signal listener' do
let(:button_class) do
Class.new do
include QML::Access
signal :pressed
property(:is_pressed) { false }
property :id
property(:is_id_changed) { false }

on :pressed do |pos|
self.is_pressed = true
end
on_changed :id do
self.is_id_changed = true
end
end
end
let(:button) { button_class.new }

describe '.on' do
it 'registers a signal listener' do
expect(button.is_pressed).to eq(false)
button.pressed.emit
expect(button.is_pressed).to eq(true)
end
end

describe '.on_changed' do
it 'registers a property change listener' do
expect(button.is_id_changed).to eq(false)
button.id = "foo"
expect(button.is_id_changed).to eq(true)
end
end
end

describe 'property' do
it 'is converted to JS objects through #to_qml' do
example = AccessExample.new
Expand Down

0 comments on commit 5662e0c

Please sign in to comment.