2013-02-24 2 views
0

Rails 3backbone-on-rails 보석을 사용하여 Rails 앱을 개발 중입니다.백본의 레일 서로 다른보기에서 컬렉션에 모델을 추가하는 방법은 무엇입니까?

ProductTypes를 보여주는 백본 경로가 있습니다. 여기에는 목록에 대한 백본보기와 양식에 대한보기가 있으므로 USar에서 새 ProductTypes를 추가 할 수 있습니다.

모든 것이 정상적으로 작동하지만 작성된 모델을 양식보기에서 목록보기의 모음으로 추가하려고하면 작동합니다. 두보기를 모두 연결하는 방법을 모르겠습니다.

다음
class Newgvbtool.Models.ProductType extends Backbone.Model 
    initialize: (model)-> 
    @company_id = model.company_id 
    @id = model.id 
    url:()-> 
    "/api/companies/#{@company_id}/product_types/" + (@id || '') 

내들이다 :

class Newgvbtool.Routers.ProductTypes extends Backbone.Router 
    routes: 
    'companies/:company_id/product_types': 'index' 

    initialize: -> 
    @container = $('#product-types-view') 
    @company_id = @container.data 'company_id' 
    @collection = new Newgvbtool.Collections.ProductTypes([],{ company_id: @company_id }) 
    @collection.fetch() 

    index: (company_id) -> 
    view = new Newgvbtool.Views.ProductTypesIndex(collection: @collection) 
    @container.append view.render().el 

    newModel = new Newgvbtool.Models.ProductType({ company_id: @company_id }) 
    editView = new Newgvbtool.Views.ProductTypeEdit model: newModel 
    @container.append editView.render().el 

그녀가 내 모델입니다 : 여기

내 경로의
# Collection view 
class Newgvbtool.Views.ProductTypesIndex extends Backbone.View 

    template: JST['product_types/index'] 

    events: -> 

    initialize: -> 
    @collection.on 'reset', @render 
    @collection.on 'add', @appendItem 
    @collection.on 'remove', @removeItem 

    render: => 
    $(@el).html @template() 
    @collection.each @appendItem 
    @ 

    appendItem: (model)=> 
    view = new Newgvbtool.Views.ProductType model: model 
    $('#product-types tbody').append(view.render().el) 

    removeItem: (model)=> 
    $('#product-types tbody').find("tr[data-id=#{model.get('id')}]").remove() 


#Item view 
class Newgvbtool.Views.ProductType extends Backbone.View 

    template: JST['product_types/product_type'] 
    tagName: 'tr' 

    events: 
    'click .delete-item': 'deleteItem' 

    initialize: -> 
    @model.on 'highlight', @highlight 
    @model.on 'change', @render 

    render: => 
    $(@el).attr('data-id', @model.get('id')).html @template(model: @model) 
    @ 

    highlight: => 
    @$('td').effect 'highlight', 1000 

    deleteItem: -> 
    @model.destroy(
     wait: true 
    ) if confirm "Are you sure?" 

#Form view 
class Newgvbtool.Views.ProductTypeEdit extends Backbone.View 

    template: JST['product_types/edit'] 

    render: => 
    $(@el).html @template(model: @model) 
    @ 

    events: -> 
    'submit #product-type-form': 'createProductType' 

    createProductType: (e) -> 
    e.preventDefault() 

    attributes = $(e.currentTarget).serializeForm()['product_type'] 

    @model.save attributes, 
     wait: true 
     success: (model)-> 
     $('#product-type-form')[0].reset() 
     model.trigger('highlight') 

가되는 방법 때문에 새로운 모델을 저장할 때 폼 뷰 주 모델에 실제로 해당 모델을 추가 할 수 있으므로 추가 이벤트가 트리거되고이 새 모델이 컬렉션보기?

항목 업데이트의 경우 목록에서 선택한 모델을 양식으로 설정하여 업데이트 할 수 있고 변경 사항을 컬렉션의보기에 반영 할 수 있습니까?

미리 감사드립니다.

+1

초기화 할 때 모델에 대한 참조를 제공 할 수 있습니다. 그렇게하면 사용자가 컬렉션을 저장할 때 모델이 컬렉션에 추가 될 수 있습니다. – Jesper

+0

전역 이벤트 "productType : save"를 설정하고 컬렉션을 바인딩 할 수 있습니다. 모델 저장시 해당 이벤트를 트리거하십시오. 그러나 모델이 여러 컬렉션에 속하면 이는 좋은 전략입니다. 나는 여전히 폼 이벤트가 호출 된 View 내부에서이 작업을 수행하는 것을 선호합니다. 모델 생성, 저장, 콜렉션에 추가 –

+0

여러분의 재사용에 감사드립니다! – bigardone

답변

0

응용 프로그램에 이벤트 수집기를 만들어보기에서 쉽게 사용자 지정 이벤트를 트리거하고 이에 반응하는 다른 수신기의 수신기를 가질 수 있습니다.

Derick Bailey 게시물에 대한 link입니다. 여기서 그는 어떻게 작동하는지 설명하고 구현 방법에 대한 몇 가지 아이디어를 제공합니다.

window.App = 
Models: {} 
Collections: {} 
Views: {} 
Routers: {} 

initialize: -> 
    @vent = _.extend({}, Backbone.Events) 
    # More code here 

$(document).ready -> 
    App.initialize() 

그런 App.vent이 이벤트 애그리 게이터 (aggregator)가 될 것이며,이 같은 이벤트를 트리거 할 수 있습니다 : 당신이 당신의 응용 프로그램을 인스턴스화하는 주요 개체를 사용하는 경우

당신은 이런 식으로 뭔가를 할 수

App.vent.trigger "model:add:success", @model 

여기서 "model : add : success"가 모델 "@model"을 전달합니다. 그런 다음 다른 위치로 가져올 수 있습니다.

initialize: -> 
    App.vent.on "model:add:success", @appendModel, this 
+0

이것은 아주 좋은 해결책입니다! – bigardone

관련 문제