"SyntaxError: unexpected }" when setting up backbone.js with rails [closed] - ruby-on-rails

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Ok, I'm baffled. I am trying to set up a rails/backbons SPA. I am following along with this railscast: http://railscasts.com/episodes/323-backbone-on-rails-part-1?autoplay=true
I get this error from the browser when trying to access the root page:
ExecJS::RuntimeError in Main#index
Showing /Users/Eamon/raffle/raffler/app/views/layouts/application.html.erb where line #6 raised:
SyntaxError: unexpected }
(in /Users/Eamon/raffle/raffler/app/assets/javascripts/backbone/models/entry.js.coffee)
Extracted source (around line #6):
3: <head>
4: <title>Raffler</title>
5: <%= stylesheet_link_tag "application", :media => "all" %>
6: <%= javascript_include_tag "application" %>
7: <%= csrf_meta_tags %>
8: </head>
9: <body>
Here is my code - I only got a few minutes into the video.
raffler.js.coffee
#= require_self
#= require_tree ./templates
#= require_tree ./models
#= require_tree ./views
#= require_tree ./routers
window.Raffler =
Models: {}
Collections: {}
Routers: {}
Views: {}
init: ->
new Raffle.Routers.Entries()
Backbone.history.start()
$(document).ready ->
Raffler.init()
entries_router.js.coffee
class Raffler.Routers.EntriesRouter extends Backbone.Router
initialize: (options) ->
#entries = new Raffler.Collections.EntriesCollection()
#entries.reset options.entries
routes:
"new" : "newEntry"
'' : 'index'
":id/edit" : "edit"
":id" : "show"
newEntry: ->
#view = new Raffler.Views.Entries.NewView(collection: #entries)
$("#entries").html(#view.render().el)
index: ->
alert "home page"
show: (id) ->
entry = #entries.get(id)
#view = new Raffler.Views.Entries.ShowView(model: entry)
$("#entries").html(#view.render().el)
edit: (id) ->
entry = #entries.get(id)
#view = new Raffler.Views.Entries.EditView(model: entry)
$("#entries").html(#view.render().el)
I know most of the above code is irrelevant at this point in the cast...it was all created by the scaffold generator - I figured I didn't have to delete anything.
entry.js.coffee
class Raffler.Models.Entry extends Backbone.Model
paramRoot: 'entry'
defaults:
class Raffler.Collections.EntriesCollection extends Backbone.Collection
model: Raffler.Models.Entry
url: '/entries'
The above file is where I think the error is occurring. I just can't seem to find a syntax error anywhere. I noticed in the code that goes with the railscast on the cast page, that entry.js.coffee just has
class Raffler.Models.Entry extends Backbone.Model
I tried deleting everything but that line for the entry.js.coffee file - when I go to the root page...it just says "Loading...," which is just a reflection of the code used as a placeholder for before the app initializes.
Maybe a fresh pair of eyes...
UPDATE
I found someone with a similar issue here:
rails: backbone-on-rails gem-
After seeing this and a few other related posts...I tried deleting the //=require_tree . line from application.js. A few other posts say it needs to be at the bottom...but mine already was, so that isn't the problem either. Incase it is relevant, here is my application.js file:
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require underscore
//= require backbone
//= require backbone_rails_sync
//= require backbone_datalink
//= require backbone/raffler
//= require_tree .

Checking your entry.js.coffee code in "Try Coffeescript" on coffeescript.org, I get the same error.
Adding {} to defaults: cleared the error and now renders correctly.
entry.js.coffee
class Raffler.Models.Entry extends Backbone.Model
paramRoot: 'entry'
defaults: {}
class Raffler.Collections.EntriesCollection extends Backbone.Collection
model: Raffler.Models.Entry
url: '/entries'

Related

Excel Add In - Javascript only working after reload

I am developing an Excel Add-In using the Office-JS Library.
When some pages are loaded, the JS is not loaded properly.
The Javascript only works after reloading the page.
I disabled turbolink as suggested in another question.
But my problem still appears.
My office_connect.js contains the following:
//= require jquery3
//= require jquery_ujs
//= require_self
//= require select2-full
//= require select2_locale_de
And the head of my layout file:
<%= yield :head_top %>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />
<%= stylesheet_link_tag "office_connect"%>
<%= javascript_include_tag "office_connect_app"%>
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js" type="text/javascript"></script>
<%= javascript_include_tag "oc_function"%>
<%= javascript_include_tag "office_excel"%>
<title><%=t('layouts.head.text_immodatacockpit')%></title>
<%= csrf_meta_tag %>
<%= yield :head %>
The oc_function file starts Office JS:
// The initialize function must be run each time a new page is loaded.
(function () {
Office.initialize = function (reason) {
// If you need to initialize something you can do so here.
};
})();
A shortened version of my excel.js:
(function () {
"use strict";
var cellToHighlight;
var messageBanner;
var config;
var sheetData;
let housing_output_template_new;
let housing_output_template_edit;
// The initialize function must be run each time a new page is loaded.
Office.initialize = function (reason) {
$(document).ready(function () {
$(".spinner").hide();
// If not using Excel 2016, use fallback logic.
if (!Office.context.requirements.isSetSupported('ExcelApi', '1.1')) {
$('#subtitle').text("Opps!");
$("#template-description").text("Sorry, this sample requires Word 2016 or later. The button will not open a dialog.");
$('#button-text').text("Button");
$('#button-desc').text("Button that opens dialog only on Word 2016 or later.");
return;
}
$("#select1").select2({placeholder: 'Please choose' , language:'<%= I18n.locale %>',dropdownAutoWidth:true});
$(".select4").select2({placeholder: 'Please choose' , language:'<%= I18n.locale %>',dropdownAutoWidth:true});
});
}
})();
I think it has something to do with the order I load the JS libraries.
Could you point me in the direction of what I am missing?
It looks like you are assigning Office.initialize in two places. If these calls are on two different pages, then that's OK. But you shouldn't be doing this twice on the same page.

Foundation 6 top-bar dropdown won't close

I added a dropdown menu to my top-bar, all the submenus appear when I hover the mouse over it.
The problem is after starting the server then when I click any link in my application then the whole submenu aligns vertically in the topbar and won't go away. When I refresh the page with F5 then the submenu items disappear but when I click any other link then they appear again in fixed position, aligned under the dropdown menu link.
Before hover:
On hover:
After clicking whatever link in the app:
To be sure I'm not messing it up myself while describing the front end, I copy-pasted example from Foundation page directly:
.top-bar
.top-bar-left
ul.dropdown.menu data-dropdown-menu=''
li.menu-text Site Title
li
a href="#" One
ul.menu.vertical
li
a href="#" One
li
a href="#" Two
li
a href="#" Three
li
a href="#" Two
li
a href="#" Three
I'm using slim for syntax and:
foundation-rails 6.4.3.0
rails 5.1.6
ruby 2.5.1
I checked the javascript console with broswer inspection tools and no errors there (also no errors in server log). I even tested with removing turbolinks in main-layout head but of course it didn't affect. I'm running out of thoughts how to debug further.
My application layout (the top-bar resides in _navbar partial which gets rendered in body):
doctype html
html lang= I18n.locale.to_s
head
meta charset='utf-8'
meta name='viewport' content='width=device-width, initial-scale=1.0'
title == content_for?(:title) ? yield(:title) : t('general.home')
= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload'
= include_gon(init: true)
= javascript_include_tag 'application'
= javascript_include_tag 'https://www.gstatic.com/charts/loader.js'
= csrf_meta_tag
= favicon_link_tag 'favicon.ico'
body
.main
= render 'layouts/navbar'
= render 'layouts/title', title: #title
= render 'layouts/messages'
= yield
And my application javascript (if somehow the order of reloading libaries should matter):
//= require jquery
//= require rails-ujs
//= require turbolinks
//= require rails.validations
//= require rails.validations.simple_form
//= require foundation
//= require chartkick
//= require ckeditor/init
//= require_tree .
$(function(){ $(document).foundation() })
Similar problem described here, but the solution isn't working for me: https://foundation.zurb.com/forum/posts/38667-foundation-62-topbar-dropdown-issue
I'ts a turbolinks issue: inside your application javascript you should load foundation on turbolinks:load like this:
$(document).on('turbolinks:load', function() {
$(function(){ $(document).foundation() })
})
Have a look at here for more information.

None of my React Components are loading inside of my html.erb files

I have this error in my browser dev tools "Calling Element.createShadowRoot() for an element which already hosts a shadow root is deprecated," which I suspect may be the issue. I also suspect that installing babel may have messed up my react-rendering, or possible the fact that I removed all my npm packages. Inside of the body tags on the browser, I have
< div data react-class="Home"> < /div>, but nothing shows up on the page. I'm using react-rails gem.
Inside my root html.erb file
< %= react_component ('Home') % >
My Home Component
class Home extends React.Component {
render() {
return()
< div>
< h1> Hello < /h1>
< /div>
}
Inside my application.js
//= require jquery
//= require jquery_ujs
//= require react
//= require react_ujs
//= require components
//= require_tree .
Inside my components.js
//= require_tree ./components
your return statement isn't correct, try:
render() {
return (
<div>
<h1>Hello</h1>
</div>
)
}
Don't forget to delete the space in your html tags right after "<".
There is problem in your render code. It must look like this :-
return ( the tags and html part will come here );
So after correction it will look like this :- (dont forget ; too)
render()
{
return(
< div>
< h1> Hello < /h1>
< /div>
);
}

Angular ui-router templates are not loading, Rails backend

I'm following along with the Angular/Rails tutorial at Thinkster and I've run into an issue which seems to be most likely be Angular-related. Everything works just fine until I get to the Angular Routing section. Simply put, the inline templates within the <script> tags do not load in the <ui-view></ui-view> element. I originally thought this may be due to having opened the page locally as a file rather than having it loaded from a server, but the same problem persists even after integrating Rails (using an older version of Sprockets, as pointed out in this similar but unrelated issue).
When I load the index page in either the browser as a file or as a URL when running the Rails server, I've inspected the HTML and, sure enough, the only thing it shows in the code are the divs and an empty <ui-view> element, indicating something just isn't adding up correctly. I've tried various things, including:
Using the newest version of ui-router (0.2.15 at this writing) rather than the version in the tutorial
Using <div ui-view></div> instead of <ui-view></ui-view>
Changing the value of 'url' in the home state to 'index.html', including using the full path to the file (file:///...)
Putting the contents of the inline <script> templates into their own files (without the <script> tags, of course) and specifying the 'templateUrl' field using both relative and full paths
Trying both Chrome and Firefox just to be extra certain
None of these things have worked, even when accessing http://localhost:3000/#/home when the Rails server is running after having integrated Angular into the asset pipeline in the Integrating the Front-end with the Asset Pipeline section of the tutorial. Indeed, the route loads but does not show anything more than a completely blank page with a lonesome and empty <ui-view> element when inspecting the HTML using Chrome's dev tools.
Given that the issue seems to occur even before the Rails portion, it does seem like something to do with Angular itself, but I've got no clue what's going on, especially since I've followed along to the letter.
I'm using Bower to manage the Angular dependencies and the HTML does show that the Angular javascript files in both the app/assets/javascripts directory and in the vendor/assets/bower_components directory are being loaded properly in the <head> section, so everything seems to be okay on the asset pipeline integration.
Versios I'm using:
Rails: 4.2.3
Ruby: 2.2.1p85
Angular: 1.4.3
ui-router: 0.2.15
The code I've got for the major moving parts is below:
app/views/layouts/application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>Test App</title>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_include_tag 'application' %>
<%= csrf_meta_tags %>
</head>
<body ng-app="testApp">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<ui-view></ui-view>
</div>
</div>
</body>
</html>
app/assets/javascripts/app.js
angular.module('testApp', ['ui.router', 'templates']).config(['$stateProvider', '$urlRouteProvider', function($stateProvider, $urlRouteProvider) {
$stateProvider
.state('home', {
'url': '/home',
'templateUrl': 'home/_home.html',
'controller': 'MainCtrl'
})
.state('posts', {
'url': '/posts/{id}',
'templateUrl': 'posts/_posts.html',
'controller': 'PostsCtrl'
});
$urlRouteProvider.otherwise('home');
}]);
app/assets/javascripts/application.js
//= require angular
//= require angular-rails-templates
//= require angular-ui-router
//= require_tree .
app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
respond_to :json
def angular
render 'layouts/application'
end
end
config/routes.rb
Rails.application.routes.draw do
root to: 'application#angular'
end
app/assets/javascripts/home/mainCtrl.js
angular.module('testApp').controller('MainCtrl', ['$scope', 'posts', function($scope, posts) {
$scope.posts = posts.posts;
$scope.addPost = function() {
if (!$scope.title || $scope.title === "")
return;
$scope.posts.push({
'title': $scope.title,
'link': $scope.link,
'upvotes': 0,
'comments': [
{'author': 'Some Person', 'body': 'This is a comment.', 'upvotes': 0},
{'author': 'Another Person', 'body': 'This is also a comment.', 'upvotes': 0}
]
});
$scope.title = "";
$scope.link = "";
};
$scope.incrementUpvotes = function(post) {
post.upvotes++;
};
}]);
app/assets/javascripts/posts/postsCtrl.js
angular.module('testApp').controller('PostsCtrl', ['$scope', '$stateParams', 'posts', function($scope, $stateParams, posts) {
$scope.post = posts.posts[$stateParams.id];
$scope.addComment = function() {
if($scope.body === '')
return;
$scope.post.comments.push({
'body': $scope.body,
'author': 'user',
'upvotes': 0
});
$scope.body = '';
};
}]);
app/assets/javascripts/posts/posts.js
angular.module('testApp').factory('posts', ['$http', function($http) {
var o = {
'posts': []
};
o.getAll = function() {
return $http.get('/posts.json').success(function(data) {
angular.copy(data, o.posts);
});
};
return o;
}]);
If any other code is required to help uncover the problem, please let me know and I'll supply anything requested.
it seems that the angular-ui-router is incompatible with the new Rails sprockets. To fix this, add this earlier version of sprockets to your gemfile:
gem 'sprockets', '2.12.3'
And then run bundle update sprockets.
This was answered a few times in other similar questions, like the one below:
Angular Rails Templates just not working
$urlRouteProvider in my code should've been $urlRouterProvider. Be sure to double-check everything, folks, and make good use of the console!

401 Unauthorized error when uploading an image to Cloudinary

I'm using ruby (2.0.0), rails (3.2.17), cloudinary (1.0.70), and jquery-rails (3.1.0). I'm getting this error only when the image upload tag is nested multiple levels deep. If it's only one level deep, I'm able to upload properly. The file upload that is generated is (cloudname, signature, and api key replaced with "xxxx" for StackOverflow):
<input
type="file"
name="file"
data-url="https://api.cloudinary.com/v1_1/xxxxxxxxx/auto/upload"
data-form-data="{"timestamp":1399504570,"callback":"http://localhost:8080/cloudinary_cors.html","signature":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx","api_key":"xxxxxxxxxxxxxxx"}"
data-cloudinary-field="page[figures_attributes][1399504574259][images_attributes][0][asset]"
class="cloudinary-fileupload
">
Which, from what I have read seems to be correct, however I am still getting {"error":{"message":"Invalid cloud_name undefined"}} when I try a direct upload.
EDIT:
The URL that it hits when attempting to upload is https://api.cloudinary.com/v1_1/undefined/upload. This makes me wonder why the URL from the data-url attribute in the input is not being used and how this URL is generated.
I'm generating the file upload tag like this:
= f.cl_image_upload :asset
My application.js looks like this:
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require ckeditor/init
//= require cloudinary
//= require_tree ../../../vendor/assets/javascripts/.
//= require_tree .
Please let me know if you need any other information. Thanks!
The problem was that I wasn't including the cloudinary_js_config script anywhere. So I just added it to the top of the form like so:
= form_for #page, :html => { :multipart => true } do |f|
= cloudinary_js_config

Resources