jQuery plugins / functions not loading after rails 3.1 upgrade - ruby-on-rails

So I just recently upgraded a large project to rails 3.1. I've got the asset pipeline set up and working. However, a lot of the plugins we use and the custom jQuery functions we've written don't seem to be getting evaluated, although the source is in application.js. For example:
(function($) {
$.fn.searchable = function() {
....
}
})( jQuery );
I see this code in application.js, but anything that tries to use it gets a javascript error, undefined function. However, if I wrap the whole thing in a function definition, and call that function on document ready, then it works.
This is a really ugly workaround. Any ideas why it's not working without wrapping in a function?
Thanks.

maybe you should take a look at 'coffeescript's namescope'. e.g.
//define your js function as:
this.some_function_name() =>
alert('hello~')
//call it as:
this.some_function_name()

Related

inject select2 in typeScript

I have problem injecting the select2 library in my TypeScript/Angular project. I don't know what else to do to make it working, I searched for some working example of but without success.
jQuery gets loaded
select2.js gets loaded
definition file select2.d.ts is there (I also have matching version)
Module is injected like that:
public init() {
var myApp = angular.module('app', [
'ui.router',
'ngCookies',
'ui.bootstrap',
'select2'
]);
...
I get an error:
Module 'select2' is not available! You either misspelled the module name or forgot to load it.
What am I doing wrong there? Any help appreciated.
You are trying to inject Select2 into your application like an Angular module. This is throwing an error because Select2 is not an angular module, it's a jQuery component.
Angular UI provides ui-select which is an Angular native version of Select2.
So I resolved this by initializing select2 in jQuery style direct in my controller...
$('select').select2();
It is probably not very nice solution but it works. If anyone got better solution feel free to post it

Heroku + Rails + Angular = Unknown provider: eProvider <- e

Feeling completely baffled. I know that several questions have been asked about this and I've read and reread all of them.
Angular (with ng-route) was working until a certain commit (I'll include images of the diffs of the js files). I've already changed what I would have expected to be the guilty party, shown here:
Changed this
app.run(function($rootScope, $http){
$rootScope.logout = function(){
$http({
url: 'logout',
method: 'GET'
}).success(function(data){
window.location = window.location.href;
});
};
});
to this
app.run(['$rootScope', '$http', function($rootScope, $http){
$rootScope.logout = function(){
$http({
url: 'logout',
method: 'GET'
}).success(function(data){
window.location = window.location.href;
});
};
}]);
However, even if I completely commit out the above code the error still persists, so I really don't think that's it. I've also commented out chunk by chunk of code and nothing seems to resolve this issue.
I've attached an image showing the diff in the commit file. Before this commit, angular was working fine on Heroku/production. Am I just being stupid and not seeing it?
http://imgur.com/SwsEeuH,oITUoY7,bQ8HKrj,tZF4HMS
Thanks in advance!
You get this kind of error when you use a JavaScript minifier that mangles a Angular dependency. Because Angular looks dependency up by argument name it can't find them.
I'm not sure what you are using to build your JavaScript into minified and merged files but you'll need to work out a way to do this in an Angular friendly way. I had a project recently that used the ngmin grunt plugin to minifier my JavaScript and started to get similar errors until I switched to ng-annotate.
A bit too late to this question I guess, but I stumbled accross the same problem but only while using Angular Material. All my dependencies were injected as suggested and everything worked fine before using Material.
My setup is Angular on a Rails 5 app runnning on production on Heroku. Even following the best practices on funciton annotation for Angular, injectin Angular Material will not work in production and will throw an UnknownProvider error unless you add the ngannotate-rails gem to your project.
This gem helps angular files be annotated correctly before the assets pipeline minifies the JS files and screws dependency injections up.

Using javascript global window variables and integration testing

There's this nifty stackoverflow post on passing variables to Javascript. It echos this railscast episode. The technique works like a charm for configuring a jquery datepicker, but cause all my javascript integration tests to fail.
Here is the code in application.html.erb
<script type="text/javascript">
<%-# commented line -%>
window.sDateFormatLocal = "<%= t 'date.formats.js_date' %>"
</script>
This is a datepicker initialization that uses it
$("input.datepicker").datepicker({
dateFormat: sDateFormatLocal,
onClose: function(value, ui) {
console.log("regular old datepicker");
}
}
It appears to work very well. The only problem, all my integration tests with 'js: true' now fail. Here are the errors I get.
Capybara::Poltergeist::JavascriptError:
One or more errors were raised in the Javascript code on the page:
ReferenceError: Can't find variable: sDateFormatLocal
When I run in browser (Chrome, Firefox) there are no errors or warnings in the console.
For completeness, a typical spec looks like this:
describe "The root" do
it "should load the page and have js working.", :js => true do
visit root_path
page.should have_content "Hello world"
end
end
Is there a setting I am missing to allow variables like this in poltergeist?
If your datepicker function is not in jQuery document ready function or similar methods such as window.onload you'll have trouble.
By default the application.js will be loaded in head, and the JS code in your html.erb later. The html and assets are loaded by browser in parallel, and very likely assets will finish loading at first. If you execute the function right away instead of waiting for document ready, the variable is undefined.
If you missed that, put such code in ready block.
A better practice for exporting server variable is, instead of put it in html body, put it on head before application.js so you won't have any problem on undefined variable.
Just to follow-up on this, in case someone in is debugging a similar problem. It turned out in this case, not every view was using the same template. For instance, the signin screen has a different head. That was causing this not to load in certain circumstances, yet not others, like the ones where my tests were failing. Bottom line, make sure when you replicate your tests, you are doing it exactly as the tests do, like in my case, passing through a signin screen.

Why isn't this method getting called from my Rails unobtrusive js template

I recently started using CoffeeScript in my Rails 3.2.14 app. Currently all of our javascript code is jumbled into application.js, which also acts as our manifest file. Our plan was to extract out the stuff into controller specific code so it is easier to maintain in the future. In our application_helper.rb file, we have this helper
def css_tag_id
"#{controller.controller_name}-#{controller.action_name}"
end
We use this for page specific CSS and JavaScript. So my first step was taking code related to our PostsController and putting it in a new file posts.js.coffee. I wrap all the code in posts.js.coffee with a check using the id on the body to ensure the code only runs on views rendered by the PostsController. This all gets compiled into one big application.js file and this is fine with me. This all works perfectly.
However, an AJAX submitted form on one of the pages hits an action in the PostsController which renders select_customer.js.erb. In this template, it calls a method that is now defined in posts.js.coffee, and for some reason no longer works.
Here is a small example of all the files involved:
posts.js.coffee:
jQuery ->
if $('#posts-new').length > 0
keywordsAccordion()
keywordsAccordion = ->
$('.accordion').accordion
'active': 0,
'collapsible': true
select_customer.js.erb
keywordsAccordion();
Is CoffeeScript compiling posts.js.coffee so that it is all namespaced or something? And I need to call methods defined in it differently now from other js templates?
I realize this may be terribly confusing, but will be so grateful is someone can help me out.
Each coffeescript file is namespaced so that its functions are only available within the same file. So keywordsAccordion() is only accessible within the posts.js.coffee file.
You can attach these functions to the window object instead, making them available anywhere:
window.keywordsAccordion = ->
...
I believe you can also use #keywordsAccordion = ->, which is shorthand for this.keywordsAccordion = -> (with this referring to the global scope)

Nothing works! jquery conflict magento

I am trying to use jquery UI based transition sliders on my homepage. I tried different jquery plugins but I always get an error in the console : jQuery is not a function or some function error related to jQuery . Plugins i have tried are Lof JSliderNews 1.0,featured-content-slider, etc..
Even after following several posts on the web , iam not able to make the plugin work at all. Jquery part doesn't work. I have used carousels and other plugins with jquery.noConflict but this time nothing works!
Here's what iam doing:
jQuery.noConflict();
jQuery(document).ready(function(){
jQuery("#featured > ul").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 5000, true);
});
I also tried replacing all $ with jQuery in the included scripts but that too doesn't work in magento. Please help, i need to finish the project soon
Have you tried putting all the jQuery stuff into a function and map the window.jQuery variable as an argument? Like so:
(function($){
//... do your jQuery thing here
})(jQuery);
BTW: "jQuery is not a function" might also be a hint that you forgot to load the jQuery library into your project.
Do you have "JS file merging" enabled? If yes, try to disable it, clear your cache and try again. It helped me once when I had a smiliar issue.
Regards

Resources