codebrew / backbone-rails Goto Github PK
View Code? Open in Web Editor NEWEasily use backbone.js with rails 3.1
License: MIT License
Easily use backbone.js with rails 3.1
License: MIT License
One example:
rails g scaffold TestCase name:string content:string
rake db:migrate
rails g backbone:scaffold TestCase name:string content:string
the router gets generated would be like:
class AppName.Routers.TestCasesRouter extends Backbone.Router
initialize: (options) ->
@testCases = new AppName.Collections.TestCasesCollection()
@testCases.reset options.testCases
...
newTestCase: ->
@view = new AppName.Views.TestCases.NewView(collection: @test_case)
...
index: ->
@view = new AppName.Views.TestCases.IndexView(test_case: @test_case)
While it should stick to camel name convention for js code, use testCase instead of test_case. And there're some other part of the code is using something like options.testCases but here you passed in test_case hence the problem like 'bind' is not a function on 'undefined' would happen.
It's very simple to fix, I created a fork and will send the pull request.
GOAL: allow submitting uploaded files via AJAX using HTML5 and native input[type=file]
instead of:
params.data = JSON.stringify(data);
use:
formData = new FormData();
$.each(data[paramRoot], function (field_name, value) {
formData.append(field_name, value);
});
$.each($('input[type=file]'), function(n, el){
$.each(el.files, function(n, file){
formData.append($(el).attr('name'), file);
});
});
params.data = formData;
params.processData = false;
params.contentType = false;
this isn't a perfect implementation
Hey all - I see a problem with the scaffolding and nested models.
When I use the scaffolding to create models, collections and views with a nested model, you wind up with a situation where you'll be appending a view to several 'tbody' tags at the same time. You might want to limit your template selectors to append data to only the first, or closest tbody tag...
When I enabled pushState the index view doesn't render. I traced it down to the views initialize method and either the bind trigger is not calling this.addAll. I'm not sure why.
If you have any ideas I'll try to generate a patch for you.
index_view.js.coffee
class A3.Views.Users.IndexView extends Backbone.View
template: JST["backbone/templates/users/index"]
initialize: () ->
_.bindAll(this, 'addOne', 'addAll', 'render');
@options.users.bind('reset', this.addAll); // THE this.addAll IS NEVER TRIGGERED?
The following line produces an error when the erb code from the intro page is pasted into a haml file under an erb tag
window.router = new Blog.Routers.PostsRouter({posts: <%= @posts.to_json.html_safe -%>});
The issue is just with the dash after html_safe
. I don't believe it's necessary for .erb files either now, but could still be valid.
The inclusion of minified version of underscore, backbone etc would be nice.
Is it possible to use mustache for templating in a backbone-rails solution? If so, is there any guidance on how to do that?
It seems the 'vendors' folder files aren't available in the asset pipeline.
I'm using 0.5.4 with all needed dependencies. I can see the vendors folder with all the needed JS files in my rails gem folder.
Hi Guys,
I've been working on the pakunok project that, among other things, will allow writing templates in HAML and get them precompiled to plain JavaScript.
To me it is very important feature, that I also believe others who write a lot of Backbone in Rails will appreciate.
So if possible, I would like to get some feedback from you guys to implement the most common scenarios that apply to backbone-rails.
A bit of info about it from the readme:
Assuming you have a file app/assets/javascripts/comment.js.hamljs
with the content:
.comment
.text= text
.author= author
Then you can require comment
from the application.js
.
This gives you access to Templates.comment
function allowing you to write JavaScript like:
var html = Templates.comment({author: 'Dima', text: 'Awesome'});
$("#commit").append(html)
The name of the template function is derrived from the file name. If the file name is weird, you still can access it via Templates['what ever it is!']
.
Some examples of file names to functions mapping:
file => Templates.file
file.js.erb.hamljs => Templates.file
file-with-dash.hamljs => Templates.fileWithDash
file_with_underscore => Templates.fileWithUnderscore
dir/foo_bar => Templates.dir_fooBar
win\dir\foo_bar => Templates.win_dir_fooBar
d1/d2/foo_bar.js.a.b.c.d => Templates.d1_d2_fooBar
Followed the example faithfully (except that model is Review instead of Post) with Rails 3.1 rc6, but encountered error in both JS and Rails log on Index load:
In JS console:
TypeError: 'undefined' is not a constructor (evaluating 'new Backbonerails.Views.Reviews.IndexView({
reviews: this.reviews
})')
In Rails log:
Sprockets::Environment#path is deprecated
/Users/.../.rvm/gems/ruby-1.9.2-p290@rails_31/gems/actionpack-3.1.0.rc6/lib/sprockets/helpers/rails_helper.rb:119:in `rewrite_asset_path'
Visually inspected application.js, and it does not appear to contain IndexView, although the other views are there.
What's the reasoning for putting both models + collections in the models
dir?
E.g. brunch uses these conventions:
app/
collections/
todos_collection.coffee
models/
todo_model.coffee
True, models + collections are closely related, but on the other hand why not follow Backbone's namespacing?
One class per file works well in Rails.
Also, it would be nice if there was some consensus so it's easy to pick up projects.
Hi there, I have followed your readme file's example for the Blog app with a Post model, however, all the files generated by the generator end in .coffee not .js.coffee. So even before doing anything, I went to check to see if I could see the Blog.js via http://dns.com/assets/backbone/blog.js and failed
I am on Rails 3.1 rc4, windows 7 64 bit, Just in case it is needed, here's my gem file
source 'http://rubygems.org'
gem 'rails', ">=3.1.0.rc4"
gem 'rake', '0.8.7'
gem "nifty-generators"
gem "mongoid"
gem "mongoid-eager-loading"
gem "bson_ext", ">1.1.5"
gem 'devise'
gem 'cancan'
gem 'hirb'
gem 'rest-client'
gem 'less' # needs the more plugin
gem 'aws-s3', :require => 'aws/s3' # s3.rb
gem 'delayed_job'
gem 'delayed_job_mongoid'
gem 'kaminari'
gem 'sass-rails', "~> 3.1.0.rc"
gem 'coffee-script'
gem 'uglifier'
gem 'sprockets', "~> 2.0.0.beta.10"
gem 'jquery-rails'
gem 'rails-backbone'
group :production do
gem 'therubyracer'
end
Dears,
in my rails controller i set an attribute of the model in the new method of the controller , but when it render the new template of backbone the default value of the attribute is displayed .
how to display the assigned attribute value from the new controller method in backbone ?
I'm probably missing something silly here but when I run my view based tests within Jasmine all of them fail due to not being able to find the JST global. Everything was passing fine before I started using JST for templating.
I've looked through the code base and can not find the JST defined so I am confused as to how, when and where this is being instantiated.
Everything seems fine when run on the server but testing views that use JST will just fail which is a pain. I can only assume that I am missing something in my jasmine.yml file but I am after hours of trawling through the net has left me stumped.
Not all Rails apps have an application.js
file. Some might have application.js.coffee
, others may use a different top-level javascript file. The install generator can't handle these edge cases.
Perhaps if application.js
can't be found instructions on what to do in your top-level javascript file could be printed.
Something like:
Unable to find application.js. You'll have to manually require the following files in your top-level javascript file.
//= require underscore
//= require backbone
//= require backbone_rails_sync
//= require backbone_datalink
//= require backbone/words
Hi there, I am using MongoDB with Mongoid, where Mongoid uses the field _id instead of id.
So if I did the example provided in the readme of rails-backbone in the index.html.erb
$(function() {
window.controller = new Blog.Controllers.PostsController({posts: <%= @posts.to_json.html_safe -%>});
Backbone.history.start();
});
I'd get "id is not defined" in the Chrome console
if I changed the above to
$(function() {
window.controller = new Kiosk.Controllers.PostsController({posts: <%= @posts.to_json.gsub('_id','id').html_safe -%>});
Backbone.history.start();
});
the difference is the gsub(), it'll display okay, and works as it should until some part of the app re-request the model directly from server where no gsub('_id', 'id') was manually done, e.g., creating a new record.
I know this can be argued that it's a mongoid thing or mongodb thing in general and not this gem's business, but is there any chance that you can allow for a customizable key what is traditionally the "id".
backbone-rails
and
rails-backbone
which is kind of frustrating
Just generated a scaffold and walking through the generated code: Most things work fine but there is problem with the edit_view.js:
render : ->
$(this.el).html(this.template(@model.toJSON() ))
this.$("form").backboneLink(@model)
return this
which gives a:
Uncaught TypeError: Object [object Object] has no method 'backboneLink'
As I understand it, the call shall link the edit-form to the update-method of the view (?!) - but I cannot find the place where this method is automagically added to the form?!
Any ideas?!
cheers
stefan
I followed the instruction to use this gem, and found this issues. but I fix it refer to your dummy test app, I copied the posts_controller code to my app. So the point is json response is different from the default scaffolding generated controller through rails 3.1.0 rc5.
Hello,
I'm trying the latest git:
//= require jquery
//= require jquery_ujs
//= require underscore
//= require backbone
//= require backbone_rails_sync
//= require backbone_datalink
//= require backbone/myapp
Sprockets::FileNotFound: couldn't find file 'underscore'
(in /Users/kain/Sites/myapp/app/assets/javascripts/application.js:11)
It seems like that the packages cannot be found. I'm going to dive into the loader code.
Hi all;
I'm using backbone-rails in a nested model example (say I have a collection of Activities, and each can have a collection of Pomodori)
I work with that app on a single page. I can load and create a series of nested views to display the data I want, but now I'm stuck when trying to perform CRUD operations on that data.
For example - say I change an attribute on my outer object, and send that data to the server. Here's what that json looks like (look at pomodori_attributes):
{"activity"=>{"name"=>"testupdate", "user_id"=>1, "id"=>3, "pomodori"=>[{"activity_id"=>3, "break_length"=>4, "completed"=>false, "id"=>12, "length"=>25, "location_id"=>nil, "note"=>"test444", "start_date_time"=>"2011-12-15T00:00:00Z"}], "pomodori_attributes"=>[{"start_date_time"=>"2011-12-15T00:00:00Z", "completed"=>false, "note"=>"test444", "break_length"=>4, "activity_id"=>3, "id"=>12, "length"=>25, "location_id"=>nil}]}, "user_id"=>"1", "id"=>"3"} art_date_time"=>"2011-12-15T00:00:00Z"}]}, "user_id"=>"1", "id"=>"3"}
what the server wants, is a hash of nested objects (although there's only one in this example (look at pomodori_attributes):
{"utf8"=>"โ", "authenticity_token"=>"iv9wYvgqLt3nldVOX4AeAifpFaSHIfEj85MsPUaMiAw=", "activity"=>{"name"=>"test", "pomodori_attributes"=>{"0"=>{"_destroy"=>"", "start_date_time"=>"2011-12-15 00:00:00", "length"=>"25", "completed"=>"0", "note"=>"test444", "break_length"=>"4", "id"=>"12"}}}, "commit"=>"Update Activity", "user_id"=>"1", "id"=>"3"} "location_id"=>nil, "note"=>"test", "start_date_time"=>"2011-12-15T00:00:00Z"}]}, "user_id"=>"1", "id"=>"3"}
any guidance on how to get my json, on an update, to look like it should for the server to accept it?
Thanks for any help.
\
One of the conditions for making this project be the canonical backbone-rails
gem at Ruby Gems is for it to support Rails 3.0. @aflatter's existing backbone-rails gem on Ruby Gems does support Rails 3.0.
Per issue [#4] he's willing to combine projects if this one would support Rails 3.0.
First off, great gem! Thanks!
Normal input fields (as scaffolded) work beautifully:
<input type="text" name="color" id="color" value="green" >
But swapping the input field for a select breaks the link and the model stops being updated:
<select name="color" id="color">
<option value="green">Green</option>
<option value="blue">Blue</option>
</select>
As a newcomer to jQuery this seems odd since in the console $('#direction').val();
returns green
|| blue
correctly.
The update function doesn't work if you follow the sample text. The reason is that backbone expects the json representation of the object to get returned under a successful save, but rails serves up a blank 200 response after update.
Not sure the best way to fix it for the tutorial, but I fixed it by changing:
format.json { render head: ok }
# to
format.json { render json: @post }
in app/controllers/posts_controller.rb
Any way this could be used as a scaffold for baseline.js on sinatra?
When I change my index view to the sample all I get is a blank page (nothing is rendered)
Is this how its supposed to be setup?
Dears,
as per the istractions i have to add the following :
<script type="text/javascript"> $(function() { // Blog is the app name window.router = new Blog.Routers.PostsRouter({posts: <%= @posts.to_json.html_safe -%>}); Backbone.history.start(); }); </script>why i can't add to my application file :
init: function() {
new App.Controllers.Documents();
Backbone.history.start();
}
after
Models: {}
Collections: {}
Routers: {}
Views: {}
and using that instead
<script type="text/javascript"> $(function() { App.init(); }); </script>and why should i add {posts: <%= @posts.to_json.html_safe -%>} which will print all the collection the the html page.
Best Regards,
Shenouda Bertel
After I create a post, then go back to /posts, I get the following error in console and nothing displayed on the page
id is not defined
at
I am trying to make sure that I can paginate results using fetch() and passing in a Jquery data object.
However when passing in say, {data:{page:3}} to fetch, Rails sees it as Parameters: {"object Object"=>nil}
I am really loving what you have done with this gem, it's a pretty awesome helper for anyone getting into backbone... Although it would be really cool if this could also output the templates using HAML Assets. I'm a huge fan of the way haml is written so much as I've almost forgotten how to do simple things in raw html :p.
Hi folks,
I have the following code in a backbone-rails view:
$(@el).droppable({
hoverClass: 'hoverTask',
appendTo: "body",
drop: (event, ui) =>
...
task_model = @options.tasks.get(task_id)
task_model.save({due: due_date}, {
success: () =>
console.log 'it was successful'
error: () =>
console.log 'error'
})
The problem is, the save is triggering error() every time, despite the rails side of thing saving successfully, the backbone side of things updating successfully, and no error being thrown in either the rails logs or the browser console. Any ideas what could be going on here?
The scaffold example won't work.
Blog only got the following four members in the latest installation
Collections
Controllers
Models
Views
In generated scaffolds, destroy sends request to server, does not remove item from @posts collection of Controllers.PostsController.
All this backbone-rails stuff is awesome
What do you think about moving model's destruction to controller? Now this logic is in view object, which looks a bit wrong ;)
There are a few pull requests handling checkboxes in ways specific to the author's needs: #24, #27, #56. I started working on a branch (here: https://github.com/ylg/backbone-rails/compare/master...checkbox_handling) building on their ideas to more generically handle checkboxes and wanted to get some thoughts before submitting a patch.
So far, what I've done is (given type === "checkbox"):
if the model's attribute holds a real Javascript array
add or remove all occurrences of the checkbox's value attribute to or from the array
else if the checkbox's value is boolean-like, e.g., true, yes, on, or 1
set the model's attribute to a boolean based on the checked status (or inverse in the case of a false value)
else
copy or clear the checkbox's value to the model's attribute
Some open questions:
In the model and scaffold generators it would be interesting to use and adapt rails naming convention.
Model would be singular and collection plural by default, it would be enforce by the generator.
class App.Models.Category
class App.Collections.Categories
Since most of the time the relationship between model and collection is 1 to 1.
And frankly App.Collections.CategoriesCollection feel a bit repetitive.
When Sprocket's debugging mode is enabled:
<%= javascript_include_tag "application", :debug => Rails.env.development? %>
The first JST file is included correctly, but the remaining are not. Instead of a .jst extension, they contain .js.
<script src="/assets/backbone/templates/todos/edit.jst?body=1" type="text/javascript"></script>
<script src="/assets/backbone/templates/todos/index.js?body=1" type="text/javascript"></script>
<script src="/assets/backbone/templates/todos/new.js?body=1" type="text/javascript"></script>
I created an app with backbone-rails scaffolding and am looking into more detail about how an app build using backbone-rails is structured.
Say I load a page of data from a URL on the server. I want to be able to debug the state of my application once the page is loaded. I can see populated views on the screen, but I can't, however, see where that instance data is. I can see option data under my application object, but that's just raw deserialzed data. I'd expect to see instance data of the app available for me to see in the console.
I can see how that collection data gets created by passing in option data to a router - but I can't see that router instance once the page is loaded.
Is there a best practice for creating that using the backbone-rails gem?
Thanks for any guidance!
It would be useful to have an option to generate the actual JavaScript, rather than CoffeeScript, for those who don't want to write in Coffee.
This is a great gem; we are not using coffee script though so the generators don't quite fit our needs. Would you be into providing a switch to generate vanilla js rather than coffee?
It seems like the format could be specified as a command line argument and/or configuration setting?
The README says this gem supports "0.9" but the currently released gem only supports 0.5.3. Can we get a gem push with the latest head? Thanks!
take the Blog example
load up localhost:3000/posts
-> create a new post
-> click 'back
-> destroy that post
-> create another post
-> click 'back'
= page has not refreshed the first post which you created and destroyed is still in the view, although it is removed from the server
I am going through the README example and trying to get the templates to render on the index page.
However, I do not see any Backbone rendered views. I see the default Rails scaffolding but not the Backbone views. I am using Rails 3.1.1 and Backbone-rails 0.5.4.
~/code/blog $ rails -v
Rails 3.1.1
~/code/blog $ bundle list | grep backbone
* rails-backbone (0.5.4)
Is there another painfully obvious step that I am missing? I apologize for the noobness of this issue. I have looked at the generated coffeescript source, looked in Firebug for JS errors, and sacrificed a live chicken, but still haven't had any luck.
I've also tried the example from this screencast: http://vimeo.com/30705694 and get the same (lack of) results.
rails new blog
cd blog
Edit Gemfile:
gem "rails-backbone", "~> 0.5.4"
bundle install
Using rails-backbone (0.5.4)
rails g scaffold Post title:string content:string
rake db:migrate
rails g backbone:scaffold Post title:string content:string
Edit app/views/posts/index.html.erb:
<script type="text/javascript">
$(function() {
// Blog is the app name
window.router = new Blog.Routers.PostsRouter({posts: <%= @posts.to_json.html_safe -%>});
Backbone.history.start();
});
</script>
rails s
Open localhost:3000
How does this handle many-to-many (HABTM) relationships between Rails models?
The directory structure is not correct when using it with a mountable engine. For example:
rails g backbone:install
tries to access application.js in:
app/assets/javascripts/application.js
while it should be:
app/assets/javascripts/{mountable app name}/application.js
The only thing that different in my stack is Mongo (Mongoid) instead of ActiveRecord so:
config.generators do |g|
g.orm :mongoid
g.template_engine :erb
g.test_framework :rspec, :fixture => true, :views => false
g.fixture_replacement :fabrication
end
Whatever I do, the generators don't show up:
Could not find generator backbone:install.
$ bundle show backbone-rails
/home/wojtek/.rvm/gems/ruby-1.9.2-p290@headspace/gems/backbone-rails-0.5.2
$ rails -v
Rails 3.1.0.rc5
Running the simple blog sample application, I am trying to understand how to make Backbone.js work for me.
When trying this in the Firebug console, I get the error as stated in the title:
posts = Blog.Models.PostModel({'name': 'test'})
postView = new Blog.Views.Posts.IndexView({model: posts})
TypeError: this.options.posts is undefined
[Bei diesem Fehler anhalten] return this.options.posts.bind('reset', this.addAll);
So, my issue would be where is options coming from, and what value would be expected?
After following the README and creating a simple model with two fields, I am unable to update the record because it's passing the id attribute in the params and that attribute is protected.
Excerpt from logs:
Started PUT "/opportunities/5" for 127.0.0.1 at 2011-09-08 16:39:29 -0500
Processing by OpportunitiesController#update as JSON
Parameters: {"opportunity"=>{"organization_name"=>"Test Org", "state"=>"new", "created_at"=>"2011-09-08T21:39:22Z", "id"=>5, "updated_at"=>"2011-09-08T21:39:22Z"}, "id"=>"5"}
Opportunity Load (0.1ms) SELECT "opportunities".* FROM "opportunities" WHERE "opportunities"."id" = $1 LIMIT 1 ["id", "5"] BEGIN
WARNING: Can't mass-assign protected attributes: id
(0.1ms) COMMIT
Completed 200 OK in 11ms
Using underscores in CoffeeScript class names is not idiomatic, it should use CamelCased names. For a project named foo_bar
the root namespace created is Foo_bar
.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.