Module: Native::Helpers

Defined in:
opal/stdlib/native.rb

Instance Method Summary collapse

Instance Method Details

#alias_native(new, old = new, as: nil) ⇒ Object

Public: Exposes a native JavaScript method to Ruby

new - The name of the newly created method. old - The name of the native JavaScript method to be exposed. If the name ends with "=" (e.g. foo=) it will be interpreted as a property setter. (default: the value of "new") as - If provided the values returned by the original method will be returned as instances of the passed class. The class passed to "as" is expected to accept a native JavaScript value.

Examples

class Element include Native::Helpers

alias_native :add_class, :addClass
alias_native :show
alias_native :hide

def initialize(selector)
  @native = `$(#{selector})`
end

end

titles = Element.new('h1') titles.add_class :foo titles.hide titles.show



138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'opal/stdlib/native.rb', line 138

def alias_native(new, old = new, as: nil)
  if old.end_with? ?=
    define_method new do |value|
      `#@native[#{old[0 .. -2]}] = #{Native.convert(value)}`

      value
    end
  else
    if as
      define_method new do |*args, &block|
        if value = Native.call(@native, old, *args, &block)
          as.new(value.to_n)
        end
      end
    else
      define_method new do |*args, &block|
        Native.call(@native, old, *args, &block)
      end
    end
  end
end

#native_accessor(*names) ⇒ Object



176
177
178
179
# File 'opal/stdlib/native.rb', line 176

def native_accessor(*names)
  native_reader(*names)
  native_writer(*names)
end

#native_reader(*names) ⇒ Object



160
161
162
163
164
165
166
# File 'opal/stdlib/native.rb', line 160

def native_reader(*names)
  names.each {|name|
    define_method name do
      Native(`#@native[name]`)
    end
  }
end

#native_writer(*names) ⇒ Object



168
169
170
171
172
173
174
# File 'opal/stdlib/native.rb', line 168

def native_writer(*names)
  names.each {|name|
    define_method "#{name}=" do |value|
      Native(`#@native[name] = value`)
    end
  }
end