Class: Browser::DOM::Element::Attributes

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
opal/browser/dom/element/attributes.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(element, options) ⇒ Attributes

Returns a new instance of Attributes.



8
9
10
11
12
# File 'opal/browser/dom/element/attributes.rb', line 8

def initialize(element, options)
  @element   = element
  @native    = element.to_n
  @namespace = options[:namespace]
end

Instance Attribute Details

#namespaceObject (readonly)

Returns the value of attribute namespace.



6
7
8
# File 'opal/browser/dom/element/attributes.rb', line 6

def namespace
  @namespace
end

Instance Method Details

#[](name, options = {}) ⇒ Object Also known as: get



15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'opal/browser/dom/element/attributes.rb', line 15

def [](name, options = {})
  if name == :class && Browser.supports?('Element.className')
    name = :className
  elsif name == :for && Browser.supports?('Element.htmlFor')
    name = :htmlFor
  end

  if namespace = options[:namespace] || @namespace
    `#@native.getAttributeNS(#{namespace.to_s}, #{name.to_s}) || nil`
  else
    `#@native.getAttribute(#{name.to_s}) || nil`
  end
end

#[]=(name, value, options = {}) ⇒ Object Also known as: set



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'opal/browser/dom/element/attributes.rb', line 29

def []=(name, value, options = {})
  if name == :class && Browser.supports?('Element.className')
    name = :className
  elsif name == :for && Browser.supports?('Element.htmlFor')
    name = :htmlFor
  end

  if namespace = options[:namespace] || @namespace
    if value
      `#@native.setAttributeNS(#{namespace.to_s}, #{name.to_s}, #{value})`
    else
      `#@native.removeAttributeNS(#{namespace.to_s}, #{name.to_s})`
    end
  else
    if value
      `#@native.setAttribute(#{name.to_s}, #{value.to_s})`
    else
      `#@native.removeAttribute(#{name.to_s})`
    end
  end
end

#delete(name) ⇒ String

Deletes an attribute with a given name

Returns:

  • (String)

    an attribute value before deletion



78
79
80
81
82
# File 'opal/browser/dom/element/attributes.rb', line 78

def delete(name)
  attr = self[name]
  self[name] = nil
  attr
end

#each(&block) ⇒ Object



86
87
88
89
90
91
92
93
94
# File 'opal/browser/dom/element/attributes.rb', line 86

def each(&block)
  return enum_for :each unless block_given?

  @element.attribute_nodes.each {|attr|
    yield attr.name, attr.value
  }

  self
end

#has_key?(name) ⇒ Boolean

Returns:

  • (Boolean)


98
99
100
# File 'opal/browser/dom/element/attributes.rb', line 98

def has_key?(name)
  !!self[name]
end

#merge!(hash) ⇒ Object



102
103
104
105
106
107
108
# File 'opal/browser/dom/element/attributes.rb', line 102

def merge!(hash)
  hash.each {|name, value|
    self[name] = value
  }

  self
end