Giter VIP home page Giter VIP logo

opal-jquery's Introduction

Opal jQuery

jQuery wrapper for Opal

Build Status

opal-jquery provides DOM access to opal by wrapping jQuery (or zepto) and providing a nice ruby syntax for dealing with jQuery instances.

Installation

Install opal-jquery from RubyGems:

$ gem install opal-jquery

Or include it in your Gemfile for Bundler:

gem 'opal-jquery'

Running Specs

Get the dependencies:

$ bundle install

Browser

You can run the specs in any web browser, by running the config.ru rack file:

$ bundle exec rackup

And then visiting http://localhost:9292 in any web browser.

Phantomjs

You will need phantomjs to run the specs outside the browser. It can be downloaded at http://phantomjs.org/download.html

On osx you can install through homebrew

$ brew update; brew install phantomjs

Run the tests inside a phantom.js runner:

$ bundle exec rake

Zepto

opal-jquery also supports zepto. To run specs for zepto use the rake task:

$ bundle exec rake zepto

Getting Started

Usage

opal-jquery can now be easily added to your opal application sources using a standard require:

# app/application.rb
require 'opal'
require 'jquery'
require 'opal-jquery'

alert "Hello from jquery + opal"

Note: this file requires two important dependencies, jquery and opal-jquery. You need to bring your own jquery.js file as the gem does not include one. If you are using the asset pipeline with rails, then this should be available already, otherwise download a copy and place it into app/ or whichever directory you are compiling assets from. You can alternatively require a zepto instance.

The #alert method is provided by opal-jquery. If the message displays, then jquery support should be working.

How does opal-jquery work

opal-jquery provides an Element class, whose instances are toll-free bridged instances of jquery objects. Just like ruby arrays are just javascript arrays, Element instances are just jquery objects. This makes interaction with jquery plugins much easier.

Also, Element will try to bridge with Zepto if it cannot find jQuery loaded, making it ideal for mobile applications as well.

Interacting with the DOM

Finding Elements

opal-jquery provides the Element class, which can be used to find elements in the current document:

Element.find('#header')

Element.find is aliased to Element[]:

Element['.my-class']

These methods acts just like $('selector'), and can use any jQuery compatible selector:

Element.find('#navigation li:last')

The result is just a jQuery instance, which is toll-free bridged to instances of the Element class in ruby:

Element.find('.foo').class
# => Element

Instances of Element also have the #find method available for finding elements within the scope of each DOM node represented by the instance:

el = Element.find('#header')
el.find '.foo'
# => #<Element .... >

Running code on document ready

Just like jQuery, opal-jquery requires the document to be ready to be able to fully interact with the page. Any top level access should use the ready? method:

Document.ready? do
  alert "document is ready to go!"
end

or the equivilent Document.ready promise which is useful when combined with other promises:

Document.ready.then do |ready|
  alert "Page is ready to use!"
end

Notice the use of the Kernel#alert method.

Event handling

The Element#on method is used to attach event handlers to elements:

Element.find('#header').on :click do
  puts "The header was clicked!"
end

Selectors can also be passed as a second argument to handle events on certain children:

Element.find('#header').on(:click, '.foo') do
  puts "An element with a 'foo' class was clicked"
end

An Event instance is optionally passed to block handlers as well, which is toll-free bridged to jquery events:

Element.find('#my_link').on(:click) do |evt|
  evt.stop_propagation
  puts "stopped the event!"
end

You can access the element which triggered the event by #current_target.

Document.on :click do |evt|
  puts "clicked on: #{evt.current_target}"
end

CSS styles and classnames

The various jQuery methods are available on Element instances:

foo = Element.find('.foo')

foo.add_class 'blue'
foo.remove_class 'foo'
foo.toggle_class 'selected'

There are also added convenience methods for opal-jquery:

foo = Element.find('#header')

foo.class_name
# => 'red lorry'

foo.class_name = 'yellow house'

foo.class_name
# => 'yellow house'

Element#css also exists for getting/setting css styles:

el = Element.find('#container')
el.css 'color', 'blue'
el.css 'color'
# => 'blue'

HTTP/AJAX requests

jQuery's Ajax implementation is also wrapped in the top level HTTP class.

HTTP.get("/users/1.json") do |response|
  puts response.body
  # => "{\"name\": \"Adam Beynon\"}"
end

The block passed to this method is used as the handler when the request succeeds, as well as when it fails. To determine whether the request was successful, use the ok? method:

HTTP.get("/users/2.json") do |response|
  if response.ok?
    alert "successful!"
  else
    alert "request failed :("
  end
end

It is also possible to use a different handler for each case:

request = HTTP.get("/users/3.json")

request.callback {
  puts "Request worked!"
}

request.errback {
  puts "Request didn't work :("
}

The request is actually triggered inside the HTTP.get method, but due to the async nature of the request, the callback and errback handlers can be added anytime before the request returns.

Handling responses

Web apps deal with JSON responses quite frequently, so there is a useful #json helper method to get the JSON content from a request:

HTTP.get("/users.json") do |response|
  puts response.body
  puts response.json
end

# => "[{\"name\": \"Adam\"},{\"name\": \"Ben\"}]"
# => [{"name" => "Adam"}, {"name" => "Ben"}]

The #body method will always return the raw response string.

If an error is encountered, then the #status_code method will hold the specific error code from the underlying request:

request = HTTP.get("/users/3.json")

request.callback { puts "it worked!" }

request.errback { |response|
  puts "failed with status #{response.status_code}"
}

Supplying an XHR method

To supply an XHR callback include a lambda with the xhr option:

update_progress = lambda do
  xhr = `new window.XMLHttpRequest()`
  update_progress = lambda do |evt|
    # update your progress here
  end
  `xhr.upload.addEventListener("progress", update_progress, false)`
  xhr
end

cloud_xfer = HTTP.put "http://my.cloud.storage/location", xhr: update_progress, ... etc ...

Usage of JQuery plugins

Extra plugins used for JQuery aren't available to ruby code by default, you will have to expose these functions to opal-jquery.

Element.expose :cool_plugin

Arguments to a exposed function will be passed as they are, so these arguments will have to be passed as native JS instead of ruby code. A conversion to native JS can be done with the .to_n method.

Element.expose :cool_plugin

el = Element['.html_element']
el.cool_plugin({argument: 'value', argument1: 1000}.to_n)

License

(The MIT License)

Copyright (C) 2013 by Adam Beynon

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

opal-jquery's People

Contributors

5t111111 avatar adambeynon avatar alexwayfer avatar andriusch avatar andyobtiva avatar arcovion avatar catmando avatar dan42 avatar devl avatar dougo avatar elia avatar elmendalerenda avatar fkchang avatar francescoagati avatar georgeu2000 avatar hmdne avatar jgaskins avatar natblow avatar papierkorb avatar roy avatar rubys avatar srfarley avatar svoboda-jan avatar thijsnado avatar tongueroo avatar wmnnd avatar zimbix avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

opal-jquery's Issues

scrollTop is not mapped properly

it appears that scrollTop is not mapped, instead we see scrollLeft to be mapped twice

alias_native :scroll_left=, :scrollLeft
alias_native :scroll_left, :scrollLeft

jQuery HTTP get failing on head

After moving to HEAD for the other issue opal/opal#616 some JQuery Ajax callback requests that were working are now failing. The request itself completes succesfully, then fails when going to run the callback.

Ruby:

require 'opal'
require 'jquery'
require 'opal-jquery'

def get_straight
  HTTP.get("/requests?straight") do |response|
    if response.ok?
      puts "straight!"
    else
      puts "failed :("
    end
  end
end

def get_callback
  r = HTTP.get( '/requests?cb' )

  r.callback { |response, status|
    puts "callback!"
  }

  r.errback { |data, status|
    puts "errback :("
  }
end

def simple_method  #element
  puts "simple_method"
end

Document.ready? do
  simple_method
  get_straight
  get_callback #Element.find("div#content")
end

Console:

request_test.js:11828 simple_method
request_test.js:3047  Uncaught NoMethodError: undefined method `callback' for #<Promise(80)>
request_test.js:3047  (anonymous function)
request_test.js:2718  def.$raise
request_test.js:2166  def.$method_missing.TMP_1
request_test.js:660   method_missing_stub
request_test.js:14430 $opal.Object.$$proto.$get_callback
request_test.js:14444 $a.$$p.TMP_4
request_test.js:12042 m.Callbacks.j
request_test.js:12042 m.Callbacks.k.fireWith
request_test.js:12042 m.extend.ready
request_test.js:12042 J
request_test.js:11828 straight!

Add Zepto support

Should be easy. HTTP needs no alteration. Element just wraps same prototype as jQuery, and Event should just wrap window.Event instead of $.Event. A simple if/else clause to determine whether jquery or zepto is loaded, and then wrap the right one.

Referring to $(this) inside .on() handler

Could you please explain how to do it properly with opal-jquery?
For instance, I may want to catch the 'input' event, and then use the $(this).val(). Didn't find out this information in the docs.

can't find file: "native"

When I'm trying to require opal-query get the following error:

can't find file: "native" in [...]

opal 0.7.2, opal-jquery 0.3.0

Element#at

Now you can code this:
puts Document['a'].at(2)['href']
and it works:it prints href attribute from third link

but I think syntax should be something like this:
puts Document['a'][2].attrs['href']

Thank you for Opal.

Add method_missing() or other alternatives?

Hello. Just discovered opal - and been playing with it since last night. Like it a lot - much better than other implementions of this idea that I've seen. Anyways, what would be great is to somehow implement or fake method missing - this way you can get native functionality instantaneously to almost any jquery lib such as jquery ui or wijmo, etc.

I was reading around and it seems that there is already native support for it (similar to method_missing - there was a dicussion on Yehuda Katz's blog) in newer version of mozilla, however that doesn't help - cause at least 50 of people still use IE and according to my largest project - in corp env that's more like 90% plus they tend to use older versions like IE 6 & IE 7

Anyways. I found some suggestions online - but non of them seem robust enough.
Right now when I needed sortable from jquery ui I did this in my app.js.opal ( integrating with rails)
( trying to implement one of the demos from jqueryui site)

in my applicaiton.html.haml file:

    :plain
      <ul id="sortable">
          <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span> Item 1</li>
          <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span> Item 2</li>
          <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span> Item 3</li>
          <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span> Item 4</li>
          <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span> Item 5</li>
          <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span> Item 6</li>
          <li class="ui-state-default"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span> Item 7</li>
      </ul>  

in my javascripts/app.js.opal

class Element
  def sortable(opacity="0.5")
    `#{self}.sortable({opacity: #{opacity}})`
  end  
  def hide(duration="slow")
    `#{self}.hide(duration)`
  end  
end  

Document.ready? do
  list = Document['#sortable']
  list.sortable(0.9).hide
end

Basically just extending Element class. It's fine I guess but I just miss method_missing :-) Any thoughts?

P.S.:

Huge props for working chaining!

Element#[] should return nil instead of empty string on missing attribute

This is totally op-ed, and can be closed as such, but I'd like to make a case for Element#[] and probably the native-aliased Element#attr to default to nil, instead of '' and undefined, respectively.

  • With my jQuery hat on, I expect $(element).attr('something') || 'default' to do something rational, as the return value is falsey when the attribute doesn't exist.
  • With my Ruby hat on, I expect element[:something] || 'default' to behave, as it'd be Hash semantics, and is burnt into my brain via years of Nokogiri and Hpricot (and further back with Beautiful Soup, lxml, and so on).
  • In Ruby interpolation context, and ERB, nil and the empty string would have equivalent output via to_s.
  • In most Javascript contexts, Opal's definition of nil works like an empty string, e.g.,
    %x{console.log("A" + nil + "B");}

As it stands, I must carefully audit DOM related-code for if node[:attr] and similar constructs. Apparently I cannot convince myself the return value will evaluate to true when the attribute is missing. I've known this documented behavior for weeks, and they still slip through.

Any opinions on this?

something wrong with set_timeout in specs

I'm trying to run the test suite using rackup in the browser (using latest master), and it seems like something odd is happening with the async/set_timeout stuff. First of all, it seems the numbers are being interpreted as seconds, not millseconds, so set_timeout 400 do will take 400 seconds to run. (I can change it to 4, and it will run in 4 seconds...) Also, when there's an error inside the block, instead of updating the page, it throws an actual error visible in the JS console.

Anyone else able to see this issue?

expose function

i tried using the qtip2 plugin for jquery, the function works with expose but it doesn't seem to take the parameters set in opal. using the x-string option works fine.

Any ideas why? did i implement it incorrectly?

  Element.expose :qtip

    @el = Element.find selector
    @tooltips = []
    @el.each do |tooltip|
      @tooltips.push tooltip
      %x{
        $(#{tooltip.get}).qtip({
          show: 'click',
          hide: 'unfocus',
          content: {
              title: {
                text: $(#{tooltip.get}).attr('title'),
                button: true
              },
              text: $(#{tooltip.get}).next('div') // Use the "div" element next to this for the content
          },
          position: {
            my: 'top left',  // Position my top left...
            at: 'bottom right', // at the bottom right of...
            target: $(#{tooltip.get}) // my target
          },
          style: {
              classes: 'qtip-bootstrap'
          }
        });
      }
      ## SEEMS BROKEN FOR NOW
      # tooltip.qtip(
      #   show: 'click',
      #   hide: 'unfocus',
      #   content: {
      #     title: {
      #       text: tooltip.attr('title'),
      #       button: true
      #     },
      #     text: tooltip.next('div') # Use the "div" element next to this for the content
      #   },
      #   position: {
      #     my: 'top left', # Position my top left...
      #     at: 'bottom right', # at the bottom right of...
      #     target: tooltip # my target
      #   },
      #   style: {
      #     classes: 'qtip-bootstrap'
      #   }
      # )
  end

opal-jquery doesn't work for me

At opal-jquery repository I try:

bundle exec rackup

and it doesn't work. It seems there is a wrong path (/assets/opal/spec/sprockets_runner.js).
The following doesn't work either:

bundle exec rake

I try opal-jquery at opal server example. I get this error:

TypeError: def is undefined

Finally, at website "try opal" it seems to work ok.

I guess it will be easy to fix. Thank you.

How to make opal-jquery work? Do I need to require it somewhere? And where?

In the docs there is no section on how to effectively use it (apart from installing it with "gem install opal-jquery" or requiring it in a Gemfile)

So far, concerning opal, I have managed to compile an "/app/application.rb" to a "/build.js" as explained in opal basic usage (rake build with a /Rakefile), but then coming to opal-jquery, how do I exactly make it available?
Do I need to require it somewhere or is it automatically called and included in the compiled js if found?

If I don't require it neither in application.rb or Rakefile then when I browse to the html page containing compiled js the js console outputs: " NameError: uninitialized constant Object::Element @ file:///.../build.js:1779"

I tried with requiring 'opal-jquery' in /app/application.rb but then "rake build" says it can't find it, so I thought I would need to require it in /Rakefile as well, which I did, so then "rake build" doesn't complain anymore, but when I browse to the page js console gives: "TypeError: dom_class is undefined @ file:///.../build.js:7470

What I am doing wrong? (Could you expand a bit the docs for this part?)
Thank you.

Using Opal-JQuery without Ruby

it would be better (and boost the popularity) if we could use opal-jquery without have to install ruby then build the source (prebuilt .js and .min.js)

Opal GEM compatibility

Hi, the new release of opal-jquery gem (0.0.10) specifies runtime dependency 'opal', '>= 0.3.43', which doesn't seem to contain the changes needed to satisfy this commit: 2f38015.

HTTP.post with hash payload results in an OPTIONS request

The following code
opal> HTTP.post('http://example.com', payload: {a: 'b'})
=> #<Promise(855)>

generates the following OPTIONS request (in Chrome, Mac OS X), with the payload data getting lost:
Remote Address:93.184.216.34:80
Request URL:http://example.com/
Request Method:OPTIONS
Status Code:200 OK

A string payload will work as expected, but that's not the ruby way:
opal> HTTP.post('http://example.com', payload: 'a=b&c=d')
=> #<Promise(967)>

Results in
Remote Address:93.184.216.34:80
Request URL:http://example.com/
Request Method:POST
Status Code:200 OK

with the payload being correctly POSTed.

jQuery is accessed via $ instead of jQuery

jQuery is not the only javascript library to use the $ variable. However, when I looked at the source of opal-jquery, it appears that it accesses jQuery via the $ variable. This will cause problems if someone used jQuery.noConflict() or anything of the like. Changing all the $s to jQuerys would fix this.

HTTP does not set ajax dataType, resulting in failure of negotiation

"Failure of negotiation" means the Accept HTTP header defaults to */* and a RESTful Rails controller having a #destroy method responding to :json and :html will default to HTML, and thus return a status 302 instead of a 204. Failure of apocalyptic scale† ensues as the browser applies DELETE verb onto the redirect location generally referring to the parent entity, which usually result in careful deletion of entities as it walks up a dependency tree (and server-side down again since said entities generally have dependent: destroy relations).

Example of a correct API request:

$.ajax type: method
       url: resource_url
       success: -> whatever()
       dataType: "json"

The following monkeypatch performs magic:

class HTTP
  alias_method :send_without_json!, :send!
  def send!
    `#{ @settings }.dataType = 'json'`
    send_without_json!
  end
end

Alternatively, passing the dataType: 'json' option to get/post/put/delete/new works, but is ugly, makes the abstraciton leaky and is prone to be forgotten.

† a.k.a how to devise the most roundabout way to clear a sizable portion of a database.

HTML object doesn't support the jQuery Deferred definition

I would really like to be able to use $.Deferred() within my Opal apps.

Through trial and error, I discovered that it is not made available through regular means. In particular, no deferred object is returned on call to get() and suchlike.

While I presume an analogous implementation would be possible withing opal ruby, I would appreciate an actual usage of jQuery's version, so that any opal code can interact better with present javascript implementations.

TIA

.css undefined

It should be handled the case in which the required attribute (with .css) has not been declared.

In jQuery returns undefined.

Enforce Element::find and Element::parse behaviour

Currently those two are equivalent:

Element.parse('<span />')
Element.find('<span />')

Conversely, those two equally work:

Element.find('#my_id')
Element.parse('#my_id')

I propose to enforce the behaviour elicited by the method names, that is case 1 line 2 and case 2 line 2 should fail ArgumentError. AFAICT testing the first character being or not being < is sufficient.

It is then arguable that Element::[] should stay an alias to Element::find or continue to mimic the kitchensink that is $().

Also, while rare since we should only get toll-free jQuery-boxed elements most of the time, there is a third case of usage of the $() function, it's to jQuery-box unboxed DOM element instances. To that end Element::find and Element::[] are equivalent, which feels weird. Maybe adding an Element#box method is in order?

Not working when transpiled using Opal 0.8.1

Hi!

I'm hammering at porting Opal Playground from it's current implementation with Middleman over to Rails.
https://github.com/fkchang/opal-playground

If you don't know it, what this does is that it sets up an iframe in which it injects opal generated JS. By "sets up" I mean loads a manifest JS file with the necessary dependencies, served via sprockets. The manifest file contains:

require 'opal'
require 'jquery'
require 'opal-jquery'

opal-jquery works very well in the Middleman version, using

opal (0.7.2)
opal-jquery (0.4.1)

However, opal-jquery fails to work with the Rails version, using

opal (0.8.1)
opal-jquery (0.4.1)

In Chrome's console I get:

Uncaught NameError: uninitialized constant Object::Document
(anonymous function) @ result_boot.js:3607
def.$const_missing @ result_boot.js:1924
Opal.get @ result_boot.js:75
(anonymous function) @ (index):9
(anonymous function) @ (index):12

My workaround was to save the opal-jquery.js file from Middleman (via sprockets) as a static file and include it, instead of using the Rails sprockets served version. Ending up with:

require 'opal'
require 'jquery'
#require 'opal-jquery'
require 'vendor/opal_jquery_072'

Since opal-jquery is at the same gem version, I suspect that something breaks when it's outputted (via sprockets) using opal 0.8.1

Element#html doesn't set html

Not sure if there is supposed to be some other way to set html content i.e equivalent to jQuery's .html(newHtml), but using it in the way I would expect (same as Element#text) doesn't do it.

el = Element.find('#container')

# This works
el.text('New text via #text')

puts el.text # prints 'New text via #text'

# This doesn't
el.html('New text via #html')

puts el.html # prints 'New text via #text'

I noticed someone on Stack Overflow asking the same question: How do I use jquery's .html( ) in opal-jquery?

HTTP.get doesn't serialize get data (#{payload}) to query string.

I may be wrong but it probably should serialize it to query string properly, but now it simply appends it like a string.
e.g. payload: {foo: "bar"} will result in {foo:bar} string appended, instead of ?foo=bar
Maybe this should go in HTTP:

%x{
      if (#{@method == "get"}) {
        payload = #{@payload.to_n};
        #{settings}.data = $.param(payload);
      }

And passing payload: {foo: "bar"} will behave as expected for HTTP.get.

Thirdparty javascript library Pure.js exposed methods causing error

I hope this is the right project to log this.

I'm trying to use opal-jquery with the pure.js (http://beebole.com/pure/documentation/get-started/) library

however when I expose the :render method - I get an error from the pure.js as if it's being triggered when exposed.

This is my application.rb

  puts "go"
  Document.ready? do  
   require "opal"
   require 'jquery'
   require 'opal-jquery'
   require 'pure.min'
    Element.expose :render
    $q = $global["$"]
    $q.('div.template').render({'site' => 'google','url' => 'http://www.google.com'}, {'a' => 'site', 'a@href' => 'url'})
   end
   puts "done"

and the error:

uncaught exception: pure error: cannot have more than one loop on a target
"cannot have more than one loop on a target" pure.min.js:14

Please let me know if you have any suggestions about this.

Element[n] throws TypeError

I expected the equivalent of JQuery's .eq(n) to be #[n] in opal-jquery.
However, only .at(n) seems to work at the moment and #[n] throws a TypeError:

require "opal-jquery"
Element.find("body").append(Element.parse("<a>test 1</a><a test 2</a>"))
elements = Element.find("a")
puts elements.length
puts elements.at(0) # <= works fine
puts elements[0] # <= "TypeError: n.toLowerCase is not a function"

For your convenience, the code on opalrb.org/try: http://ur1.ca/i454e

Missing native wrapping of Element#prop yields to JS errors

Hi,

Over at opal/opal#1049 I found that by trying to test for the existence for a specific DOM property, that Element#prop at least, and probably others too, don't wrap undefined. This leads to issues in the generated JavaScript, as Opal does not expect undefined to appear as variable value.

In my app, I use the following work-around. If it's helpful, feel free to make use of it:

class Element
  def property(name, toggle = nil)
    return prop(name, toggle) unless toggle.nil?

    `(self.prop(#{name}) === true || self.prop(#{name}) === "true")`
  end
end

Using element.on(:click) {<code>} seems to accumulate "on(:click)" events?

Hi

I am using this code:

def select_page id
  puts "Selected Page: #{id}"
  @page_edit_btn.remove_class "disabled"
  @page_edit_btn.on(:click) { edit_page( id ) }
end

def edit_page id
  puts "Editing page: #{id}!"      
end

This code is (in my mind) supposed to set only one "on click" attribute to the edit button. The user selects a page item and can then edit it by pressing the "Edit" button. But it seems to add one instead, everytime this script is run.

If I click on five different page items in the list and click the 'edit' button, then I will get 5 lines of log output; "Editing page " from the "edit_page" method.

Is this the expected behavior, or am I supposed to nil on(:click) somehow each time?

Thanks!

how can I build rquery?

I'm not be able to build rquery. All that gem stuff is a mess for me (I'm a poor newbie). If only I could build rquery just typing "rake rquery" (like "rake opal").

Thank you again for Opal!

Use new native features of opal

Opal can now call native methods directly on objects. This means that instead of aliasing a lot of native functions as ruby methods, we can just get method_missing to do this for us.

There is no reason to not add our own methods as we see fit, but these should be just syntax nice-ness where possible, e.g. #val= and #text=.

Is there a better way to make an HTTP call?

request = HTTP.get( "/pages/#{ page }" )
request.callback {
  ...
}

This code works great, but it feels weird because Ruby would wait until the request comes back before continuing. I guess in Javascript it's not blocking because there are other things happening...

Is there a better Ruby syntax that can be used that is asynchronous or makes more sense?

using the xhr option in an HTTP.put

Not at all sure how to do this...
I am trying to add an XHR call back to an "Opal-JQuery" HTTP.put method call.

Its not clear what goes in the XHR option. In jQuery its a function that will create and return the XHR object.

Not clear what to do when doing this with opal.

For example HTTP.put("my.big.url", xhr: what_goes_here)

I have tried various options and looked through the code... I can't figure it out.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.