APR.
27

Developers like to discuss the preference js library from jQuery to Prototype. I am not writing this post to say I would like to choose one of them. Actually I want to tell you some ways to combine them together.

jQuery is easy to use, faster and have many advanced plugins, but Prototype is more powerful and you can have a native helper methods embedded in Rails if you are using Rails to develop something. So I would like to show you 2 ways of combine them together in one application

1, jQuery official web site way : You can use jQuery.noConflict() method to announce you are using some other libraries with. Then from now on you can use jQuery as namespace instead of our favorite symbol $. Or you can provide an alias name for $ for example “var $j = jQuery.noConflict();”, then you can use $j instead of $. I don’t like this way to be honest. It will confuse people and it is inconvenient to me. Usually people who are using jQuery they don’t need to use prototype at the same time, vice versa. So here is my way

2, In this way I use some specific Rails features. I use asset packager to merge my javascripts and stylesheets. So my asset_packages.yml file may look like this:

--- 
javascripts: 
- prototype: 
  - prototype
- jquery:
  - jquery
stylesheets: 
- base: 
  - scaffold

Now you see I have two different sets of javascripts, one is prototype and the other is jquery. My layout file header in html may look like this:

<head>
  <meta http-equiv="content-type" content="text/html;charset=UTF-8" />
  <title><%= controller.action_name %></title>
  <%= yield :javascirpts %>
  <%= stylesheet_link_tag 'scaffold' %>
</head>

“yield :javascripts” tells Rails I will declare javascripts into header later. Then the most important parts, suppose I have two files(listing projects and new project), for listing projects I want to use Prototype and the other I want to use jQuery.

<% content_for :javascirpts do %>
  <%= javascript_include_merged :prototype %>
<% end %>

<h1>Listing projects</h1>

<table>
  <tr>
  </tr>

<% @projects.each do |project| %>
  <tr>
    <td><%= link_to 'Show', project %></td>
    <td><%= link_to 'Edit', edit_project_path(project) %></td>
    <td><%= link_to 'Destroy', project, :confirm => 'Are you sure?', :method => :delete %></td>
  </tr>
<% end %>
</table>

<br />

<%= link_to 'New project', new_project_path %>

The most important part is using “content_for :javascripts” block to use prototype. The other file is similar but use jquery library.

<% content_for :javascirpts do %>
  <%= javascript_include_merged :jquery %>
<% end %>
<h1>New project</h1>

<% form_for(@project) do |f| %>
  <%= f.error_messages %>

  <p>
    <%= f.submit 'Create' %>
  </p>
<% end %>

<%= link_to 'Back', projects_path %>

But this probably means you need to maintain two sets of javascripts code. That may cost a little bit much than just using one library. You need to consider before you really want to do this.

0 comments. post a comment 我要评论