0

我正在为一个学习项目构建一个小黑客新闻阅读器,其中我正在阅读的 API 有点非标准(所以除非有人知道如何硬塞它,否则 ember-data 是不可能的)。

项目列表在这里: http: //node-hnapi.herokuapp.com/news而单个项目是这样的:http: //node-hnapi.herokuapp.com/item/6696691

这是我到目前为止所做的事情:http: //jsbin.com/OFeCoR/22/edit ?html,js,output

App = Ember.Application.create()

baseURL = "http://node-hnapi.herokuapp.com"
newsURL = "/news"
itemURL = "/item/"

App.Items = Ember.Object.extend(  
  id: ""
  title: ""
  url: ""
  points: ""
  user: ""
  time_ago: ""
  comments_count: ""
  slug: (->
    @get("id")
  ).property("id")
)

App.Items.reopenClass 
  all: ->
    Ember.$.getJSON(baseURL + newsURL).then (response) ->
      items = []
      response.forEach (n) ->
        items.push App.Items.create(n)
      items     

App.Router.map ->
  @resource "items", ->
    @route "item",
      path: ":slug"

App.IndexRoute = Ember.Route.extend
  beforeModel: ->
    @transitionTo "items"

App.ItemsRoute = Ember.Route.extend
  model: ->
    App.Items.all()

App.ItemsItemRoute - Ember.Route.extend
  model: (params) ->
    itemID = App.Items.findProperty("id", params.id)
    Ember.$.getJSON((baseURL + itemURL + itemID).then (response) ->
      item = []
      response.forEach (i) ->
        item.push App.Item.create(i)
      item
    )

基本上,我试图从项目中的“项目”中获取 ID 以将其用于 slug 并在 ItemsItemRoute 中,将其推入 URL 以获取单个项目属性。我认为这是我出错的地方(ItemsItemRoute)。

我认为仅在单击链接/操作时才获取单个项目数据而不是从一开始就获取所有项目数据可能是有意义的。关于如何解决这个问题的任何想法?

4

2 回答 2

1

App.ItemsItemRoute有一些错误:

# you are using minus (-) this is a assigment and a equals (=) is needed
App.ItemsItemRoute - Ember.Route.extend
  model: (params) ->
    # App.Items.findProperty don't exist and params.id isn't present just params.slug because you mapped your route with path: ":slug"
    itemID = App.Items.findProperty("id", params.id)
    Ember.$.getJSON((baseURL + itemURL + itemID).then (response) ->          
      item = []
      # this will return just one item, no forEach needed
      response.forEach (i) ->
        item.push App.Item.create(i)
      item
    )

我更新到以下内容:

App.ItemsItemRoute = Ember.Route.extend
  model: (params) ->    
    Ember.$.getJSON(baseURL + itemURL + params.slug).then (response) ->
      App.Items.create(response)

并在每个项目中添加了一个 {{link-to}} 以便能够过渡到ItemsItemRoute

这是更新的 jsbin http://jsbin.com/OlUvON/1/edit

于 2013-11-09T00:36:53.323 回答
1

如果您想拥有一个与父资源分开的资源,您应该将您的路由器更改为以下内容:

App.Router.map ->
  @resource "items"
  @resource "item",
    path: ":slug"

但是,如果您只想获取已经获取的模型并保持相同的外观,则没有理由重新获取数据,因为您已经获取了数据,您应该只使用 modelFor 并从父资源中获取它

http://jsbin.com/eCOzOKe/1/edit

App.ItemsItemRoute = Ember.Route.extend
  model: (params) ->
    itemsModel = @modelFor("items")
    item = itemsModel.findProperty("id", params.slug)
    item

此外,您不需要使用 slug 这个词,您可以使用:id并从模型中删除只返回idas的计算属性slug

于 2013-11-09T00:12:43.460 回答