Coder Social home page Coder Social logo

opal-jquery's Introduction

opal-jquery

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. opal-jquery is hosted on github.

jQuery instances are toll-free bridged to instances of the ruby class JQuery, so they can be used interchangeably. The Document module also exists, which provides the simple top level css selector method:

elements = Document['.foo']
# => [<div class="foo">, ...]

elements.class
# => JQuery

elements.on(:click) do
  alert "element was clicked"
end

Getting Started

Installation

Install opal-jquery from RubyGems:

$ gem install opal-jquery

Or include it in your Gemfile for Bundler:

gem 'opal-jquery'

Interacting with the DOM

Finding elements

opal-jquery provides the Document module, which is the best way to find elements by CSS selector:

Document['#header']

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

Document['#navigation li:last']

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

Document['.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 = Document['#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

The Kernel#alert method is shown above too.

Event handling

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

Document['#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:

Document['#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:

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

CSS styles and classnames

The various jQuery methods are available on Element instances:

foo = Document['.foo']

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

There are also added convenience methods for opal-jquery:

foo = Document['#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 = Document['#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}"
}

opal-jquery provides DOM access to opal by wrapping jQuery and providing a nice ruby syntax for dealing with jQuery instances. opal-jquery is hosted on github.

See the website for documentation.

Running Specs

Get the dependencies:

$ bundle install

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

Build dependencies, opal-jquery and it's specs into build/:

$ rake opal

Run the tests inside a phantom.js runner:

$ rake

You can also run the tests in the browser by opening spec/index.html.

Development Tips

The following rake task are pertinent to adding/changing functionality.

  • opal - builds the following js files:
    • opal-jquery - opal jquery
    • opal.js - the opal runtime
    • opal-spec.js - opal spec framework
    • specs.js - the spec
  • opal:test - runs the specs. It is the default rake task

If you TDD, you may want to run

$ rake opal opal:test

Or use a guard script that does similar

License

Copyright (C) 2012 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

adambeynon avatar devl avatar elia avatar fkchang avatar francescoagati avatar

Watchers

 avatar

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.