markdown Rails和Backbone.js设置
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Rails和Backbone.js设置相关的知识,希望对你有一定的参考价值。
## Backbone and Rails
### Structure:
`app/assets/javascripts`
```
app/assets/javascripts:
├── application.js
├── backbone.js
├── cable.js
├── channels
├── collections
│ └── Posts.js
├── main.js
├── models
│ └── Post.js
├── pages.coffee
├── posts.coffee
├── routers
│ └── AppRouter.js
├── underscore.js
└── views
├── AppView.js
├── PostListView.js
└── PostView.js
```
### inside `application.js` file
Commented out by `javascript` but `Ruby` still runs them, load them
```javascript
//= require jquery
//= require jquery_ujs
//= require underscore
//= require backbone
//= require_tree ./models
//= require_tree ./collections
//= require_tree ./views
//= require_tree ./routers
//= require_tree .
```
### MVC
#### `main.js`:
```javascript
app.posts = new app.Posts();
app.router = new app.Router();
// load Rails post items via
app.post.fetch();
// and then start Router, like this:
$(document).ready(function(){
app.posts.fetch().done(function(){
Backbone.history.start();
});
});
```
#### `routers/AppRouter.js`:
```javascript
routes:{
'': 'index',
'posts/:id': 'showPost'
},
index: function(){
var av = new app.AppView({
collection: app.posts
});
av.render();
}
```
#### `views/AppView.js`:
```javascript
render: function(){
// default template skeleton
this.collection.each(function( post ){
var plv = new app.PostListView({
model: post
});
plv.render();
}); // each model in collection
}
```
#### `views/PostListView.js`:
```javascript
tagName: 'li',
render: function(){
var title = this.model.get('title');
this.$el.html(title);
this.$el.appendTo("#posts");
},
events: {
"click": "showPost"
},
showPost: function(){
var id = this.model.get('id');
app.router.navigate('/posts/' + id, true );
}
```
#### `views/PostView.js`
```javascript
el: "#app", // overwrite from the top level
render: function(){
var rawTemplate = $('#PostViewTemplate').html();
var template = _.template( rawTemplate );
var markup = template(this.model.attributes);
this.$el.html( markup );
}
```
### html template
usually in pages controller (in `app/views/pages/app.html.erb`)
- one template for the app, app ui, and a list of post
```html
<script type="html/template" id="AppViewTemplate">
<div id="appView">
<h1>My Blog with all my feelings</h1>
<nav>
<a href="#">All Posts</a>
<a href="#">A Post</a>
</nav>
<hr>
<ul id="posts"></ul>
</div>
</script>
```
- one template for the content(post)
```html
<script type="html/template" id="PostViewTemplate">
<div id="postView">
<h2>
{{ title }}
</h2>
<h3>
by: {{ author }}
</h3>
<p>
{{ content }}
</p>
</div>
</script>
```
以上是关于markdown Rails和Backbone.js设置的主要内容,如果未能解决你的问题,请参考以下文章
markdown 在Rails中使用.js文件和AJAX进行渲染
markdown Instalar Ruby,Ruby on Rails和PostgreSQL(Mac y Debian / Ubuntu)
markdown [rails:devise] Ruby on Rails的身份验证gem。 #ruby #rails
Backbone.stickit 和 html-form:如何只保存(补丁)更改的属性?
markdown 升级Rails
markdown Rails新