2011-11-19 3 views
0

은 백본에 며칠 동안 문제가 발생했으며이를 해결하거나 stackoverflow에서 해결책을 찾는 방법을 찾을 수 없습니다. 처음 두 경우Rails + Backbone.js :보기에서 객체에 액세스하는 데 문제가 발생했습니다.

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) 

: 여기

이 (그들 모두에서 동일한 문제) 예를 들어 내보기 중 하나입니다 :

나는 레일 3.1 + 최신 백본 (+ 커피 스크립트)를 사용 예제를 실행할 때 브라우저는 @ options.payment_methods가 정의되어 있지 않다고 말하고, 세 번째 경우는 정상적으로 작동합니다.

두 번째로 이미 페이지에 "하드 코드 된"DOM 요소에 액세스 할 수 없으며 자바 스크립트에 의해 만들어지지 않습니다. 나는 그 이유를 알고 그것에 대해 Stackoverflow에 게시물의 loooot을 읽고 있었지만 어떤 해결책을 얻을 수 없었습니다. 어떤 힌트도 크게 감사드립니다.

안부, 필

편집 : 그것은이 페이지의 하드 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 : 내 해당 라우터 파일을 추가 :

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' 
+0

입니다 제가 틀릴 수도 있지만 문제의 증상은 여기 것과 일치하는 것 - HTTP : //lostechies.com/derickbailey/2011/11/09/backbone-js-object-literals-views-events-jquery-and-el/ – vikmalhotra

+0

Hehe thanks! 나는 어제 그 증상에 필적하는 것처럼 보였기 때문에 그 포스트를 우연히 발견했습니다. 아직 성공하지 못했습니다! : -/ – user966041

답변

0

->=>의 차이점을 실제로 찾아보고 이해해야합니다. 클래스의 대부분의 메소드가 ->을 사용하고있는 것처럼 보입니다. =>을 사용해야합니다. 당신이 @something을 사용한다면, 그것은 바로 this.something의 지름길이며, =>this이 실제로 당신이 기대하는 바를 확실히합니다. ->을 사용하면 this이 클래스 인스턴스가 아니라 호출하는 함수에 바인딩됩니다.

0

옵션은보기의 initialize 메소드에 전달됩니다. 그래서 당신은 직접 그런 식으로 액세스 할 수 있습니다. 즉, 다른 콜백에서보기의 컨텍스트에서 호출되지 않는 렌더링 경우를 제외하고, 잘해야한다 render()에서 @options를 호출

initialize: (options) -> 
    # Now you have options 
    options.payment_methods.bind(###stuff###) 

. 이 문제를 해결하려면 render을 굵은 화살표로 정의하면 뷰의 컨텍스트에서 항상 호출됩니다. 이 페이지에 이미있는 요소에 액세스하려면

render: => 
    $(@el).html(...etc...) 

, 당신이해야 할 몇 가지가있다. 가장 중요한 것은 el의 DOM 요소를보기 생성자에 전달하면보기가 해당 요소를 소유하고 그 요소를 소유하게된다는 것입니다. 예를 들어 ..

view = new Blog.Views.Payment.PaymentView(
    el: $("#product_whatever").get(0) 
) 

그런 다음보기에서 jQuery가 뷰의 요소를 검색 범위로 지정하려고합니다.예를 들어 :

render: => 
    $(@el).find('div.somewhere_else').html("change this") 

커피 스크립트에서 이에 대한 백본 바로 가기

@$('div.somewhere_else').html(...) 

행운

+0

@maxlOrd 귀하의 설명에 많은 감사드립니다. "render : =>"alert @ options.payment_methods.get (1) .get ('payment_type') "하면 this.options.payment_methods.get (1)이 정의되지 않았습니다."오류가 발생합니다. 올바른 데이터로 경고를 표시합니다. 이견있는 사람? – user966041

+0

Blog.Routers.PostsRouter를 인스턴스화하고이 모든 것을 시작하는 코드가 문서 준비가 완료된 후에 실행되는지 확인하십시오. – maxl0rd

관련 문제