2013-12-19 53 views
1

在觀看Ryan Bates Railscast之後嘗試拾取Backbone,我不知道如何從我的Rails控制器傳遞多個實例變量並在我的Backbone視圖中渲染它們。任何幫助將不勝感激。我試過類似的東西:將多個對象傳遞給Rails 4中的骨幹視圖

respond_with({ photos: @photos, feature: @feature, only: @categories }) 

但我不知道如何在我的Backbone視圖中傳遞它們。

class PhotosController < ApplicationController 
    respond_to :html, :json 

    def index  
    photo = Five00px::Photo.new("jfvYEpvJLv06t0blEKNPuJyU3vjqQP6vnXh6KX3O") 
    options = { 
     consumer_key: photo.consumer.key, 
     feature: params["feature"] ? params["feature"] : "popular", 
     image_size: 2 } 

    @photos  = photo.photo_stream(options).photos 
    @feature = photo.stream_feature 
    @categories = photo.stream_categories 

    respond_with @photos 
    end 
end 

路由器:

class Five00.Routers.Photos extends Backbone.Router 

    routes: 
    "" : "index" 

    initialize: -> 
    @collection = new Five00.Collections.Photos() 
    @collection.fetch() 

    index: -> 
    photo_view = new Five00.Views.PhotosIndex(collection: @collection) 
    $("#photos").html(photo_view.render().el) 

查看:

class Five00.Views.PhotosIndex extends Backbone.View 

    template: JST['photos/index'] 

    initialize: -> 
     @collection.on("sync", @render, this) 

    render: -> 
     $(@el).html(@template(photos: @collection)) 
     this 

回答

0

我覺得你有你怎麼可能指望用骨幹應用工作的誤解。如果考慮在索引操作中創建的實例變量,那些變量通常用作視圖中的可訪問對象。對於Backbone應用程序,一旦呈現視圖,您只能訪問視圖呈現時的數據。喜歡的東西:

<script><%= "window.categories = JSON.parse(#{@categories.to_json});" %></script> 

一個辦法是讓你的照片模式包括其他關係,當你讓又名查詢:

Photo.includes(:categories) 

,並指定你想要一張照片,被序列化的方式: https://github.com/rails-api/active_model_serializers因爲你想要的是骨幹集合從你的瀏覽器獲取資源,也就是說從Photo#index操作響應JSON。

最後,要通過Backbone完全處理這個問題,併爲每個資源創建三個單獨的請求,並通過模型和集合類在前端組裝關係。您可以手動設置這些關係,也可以使用擴展骨幹庫來完成此操作,您可以查看http://backbonerelational.org/

相關問題