所以我问了这个问题:在backbone.js + rails中渲染视图
由于人们指出我正确的方向,我觉得我已经接近答案了。我的 app/views/home/index.html.erb 中的代码:
<div id="container">Loading...</div>
<script type="text/javascript">
$(function() {
window.newView = new Example.Views.Users.NewView({model: users});
//$('body').html(newView.render().$el)
console.log(newView.render().$el)
//newView.render();
Backbone.history.start();
});
</script>
当我尝试加载此页面后检查 firebug 控制台时,我收到错误消息:
ReferenceError: users is not defined
[Break On This Error]
window.newView = new Example.Views.Users.NewView({model: users});
这是其余的相关代码。
资产/javascripts/backbone/views/users/new_view.js.coffee
Example.Views.Users ||= {}
class Example.Views.Users.NewView extends Backbone.View
template: JST["backbone/templates/users/new"]
events:
"submit #new-user": "save"
constructor: (options) ->
super(options)
@model = new @collection.model()
@model.bind("change:errors", () =>
this.render()
)
save: (e) ->
e.preventDefault()
e.stopPropagation()
@model.unset("errors")
@collection.create(@model.toJSON(),
success: (user) =>
@model = user
window.location.hash = "/#{@model.id}"
error: (user, jqXHR) =>
@model.set({errors: $.parseJSON(jqXHR.responseText)})
)
render: ->
$(@el).html(@template(@model.toJSON() ))
this.$("form").backboneLink(@model)
return this
users_router.js.coffee
class Example.Routers.UsersRouter extends Backbone.Router
initialize: (options) ->
@users = new Example.Collections.UsersCollection()
@users.reset options.users
routes:
"new" : "newUser"
"index" : "index"
":id/edit" : "edit"
":id" : "show"
".*" : "index"
newUser: ->
@view = new Example.Views.Users.NewView(collection: @users)
$("#users").html(@view.render().el)
index: ->
@view = new Example.Views.Users.IndexView(users: @users)
$("#users").html(@view.render().el)
show: (id) ->
user = @users.get(id)
@view = new Example.Views.Users.ShowView(model: user)
$("#users").html(@view.render().el)
edit: (id) ->
user = @users.get(id)
@view = new Example.Views.Users.EditView(model: user)
$("#users").html(@view.render().el)
查看对旧问题的评论,您几乎可以看到我来自哪里 - 以及我尝试了什么。谢谢!
更新
用户.js.coffee
class Example.Models.User extends Backbone.Model
paramRoot: 'user'
defaults:
name: null
email: null
class Example.Collections.UsersCollection extends Backbone.Collection
model: Example.Models.User
url: '/users'