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.


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

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


4
5
6
# File 'opal/browser/dom/element/attributes.rb', line 4

def namespace
  @namespace
end

Instance Method Details

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


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

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


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

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


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

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

#each(&block) ⇒ Object


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

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)

96
97
98
# File 'opal/browser/dom/element/attributes.rb', line 96

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

#merge!(hash) ⇒ Object


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

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

  self
end