Friday, February 6, 2015

Dry concept for implementing JS plugins - tokeninput

Rails is always suggesting us to use DRY concept in our codes, and there are plenty of ways to achieve that.

Here I am gonna explain how we can achieve the DRY concept in adding JavaScript functionality to our Rails applications.

For explanation I have taken jQuery Tokeninput as an example.

Usually we add a plugin to our app in the following way.


Consider, the same html page is having auto complete for 3 elements.  Then you have to repeat the same code 3 times.  If the auto complete is added for many elements in the app, then you have to repeat the same code wherever it is necessary.

The same can be rewritten like below


In html.erb you can call the function like below

<% selected_countries = @user.countries.map { |c| { id: c.id, name: c.name } } %>
<%= text_field_tag("users[country_id]", {}, { :class => "auto_complete", "data-url" => "/users/get_countries", "data-duplicate" => "false", "data-selection-limit" => "10", "data-hint-text" => "Type to search  Country", "data-no-result" => "No Country found", "data-searching-text" => "Fetching Countries", "data-selected" => (selected_countries).to_json }) %>

By this way, wherever you need the autocomplete, just add the class 'auto_complete', or the class whatever you want.  Then that text field will be converted as auto complete dynamically based on the data attributes passed to the function.  So this will drastically reduce your code repetition on JavaScript side.

And you can easily call this same function on ajax success also, no need to load the JavaScript file one more time.

Above mentioned code example is for jquery tokeninput plugin, but the same behavior can be used in other plugin implementation too.

No comments:

Post a Comment