【发布时间】:2011-11-19 09:23:07
【问题描述】:
几天来骨干遇到问题,无法找到解决方法或在 stackoverflow 上找到解决方案。
我使用 Rails 3.1 + 最新的主干(+ coffeescript):
这是我的一个观点作为例子(所有观点都存在同样的问题):
Blog.Views.Payment ||= {}
class Blog.Views.Payment.PaymentView extends Backbone.View
className: 'payment_method'
tagName: 'td'
events:
'click #renderPayment': 'renderPayment'
initialize: ->
# CAN'T access @options.payment_methods here
@options.payment_methods.bind(###stuff###)
render: ->
# CAN'T access @options.payment_methods here either...
$(@el).html ("### something with #{@options.payment_methods or @options.payment_methods.model}")
return @
updateView: ()->
# updating view stuff...
renderPayment: ->
# ACCESSING @options.payment_methods fine here!!!
if ($("#payment_details").length == 0)
$(@el).append("<ul id='payment_details'>
<li id='payment_type'>#{@options.payment_methods.get(1).get('payment_type')}</li>
</ul>
").effect("highlight", 700)
在我运行示例的前两种情况下,浏览器告诉我 @options.payment_methods 未定义,第三种情况正常。
第二件事是我无法访问任何已经“硬编码”到页面中并且不是由 Javascript 创建的 DOM 元素。我知道其中的原因,并且一直在 Stackoverflow 上阅读大量关于它的帖子,但我找不到任何解决方案。任何提示都非常感谢。
最好的问候, 菲尔
编辑: 似乎与页面上对象的访问时机有关,类似于对页面硬编码DOM元素的访问。如果我按如下方式编辑我的视图,我将无法再访问@options.payment_methods,即使我之前能够在代码中访问。
# changed "renderPayment" to "$(document).ready" or just "$" in coffeescript
$ ->
# ACCESS NOT possible anymore
if ($("#payment_details").length == 0)
$(@el).append("<ul id='payment_details'>
<li id='payment_type'>#{@options.payment_methods.get(1).get('payment_type')}</li>
</ul>
").effect("highlight", 700)
EDIT2:添加了我相应的路由器文件:(这只是主干导轨 gem 示例“博客”的修改版本)
class Blog.Routers.PostsRouter extends Backbone.Router
initialize: (options) ->
@posts = new Blog.Collections.PostsCollection()
@posts.reset options.posts
# ... other collections
# fetch payment_methods collection
@payment_methods = new Blog.Collections.PaymentMethodsCollection()
@payment_methods.reset options.payment_methods
@payment_methods.fetch()
@model = ({posts: @posts, mails: @mails, addresses: @addresses, purchases: @purchases, payment_methods: @payment_methods})
routes:
"/new" : "newPost"
"/index" : "index"
"/:id/edit" : "edit"
"/:id" : "show"
".*" : "index"
# main view
index: ->
# render Product Info View
@view = new Blog.Views.Product.ProductView(purchases: @purchases)
$("#product_1").html(@view.render().el)
##### view etc.
# render Payment View
@view5 = new Blog.Views.Payment.PaymentView(payment_methods: @payment_methods)
$("#customer_1").append(@view5.render().el)
### other views...
还有我的付款模式:
class Blog.Models.PaymentMethod extends Backbone.Model
paramRoot: 'payment_method'
defaults:
payment_type: null
# ...
class Blog.Collections.PaymentMethodsCollection extends Backbone.Collection
model: Blog.Models.PaymentMethod
url: '/payment_methods'
【问题讨论】:
-
我可能错了,但您的问题症状似乎与这里的症状相符 - lostechies.com/derickbailey/2011/11/09/…
-
呵呵谢谢!我昨天偶然发现了那个帖子,因为它似乎真的符合我的症状。还是没有成功! :-/
标签: ruby-on-rails dom view backbone.js coffeescript