簡體   English   中英

Ember 2.0如何使模板和路由互相對話?

[英]Ember 2.0 How can I make template and route talk to each other?

我正在自學Ember-cli,並嘗試構建一個簡單的應用程序,該應用程序在用戶搜索術語時獲取結果。 我得到的ajax結果很好,但是我不確定如何將其“傳遞”給模板

這是我現在的hbs代碼/app/templates/product-search.hbs:

搜索字段可以正常工作。

<p>*Is 'xyz' by deafult. </p>
{{input class="form-control" id="search-string" type="text" value=this.search-string placeholder="Search by Product"}}
<button type="button" {{action "searchByProduct" this.search-string}}>Lookup Product</button>

<ul>

    {{#each result as |item|}}
        <li>Product Name: {{item.prodName}}</li>
    {{else}}
            Sorry, nobody is here.
    {{/each}}
</ul>

這是路由文件:/app/routes/product-search.js

import Ember from 'ember';

export default Ember.Route.extend({  
    actions: {
        searchByProduct:  function(qString) {
            var term = qString || 'xyz';
            var fetchURL = 'http://some-api.com/search?callback=JSON_CALLBACK&limit=10&term='+term;
            var result = Ember.Object.create({

            });
            return $.ajax({
              url: fetchURL,
              dataType: 'jsonp'
            }).then(function (response) {
                result.set('content', response.results);
                result = result.get('content');
                console.log("Search Result In Then Promise of Model: ");
                console.log(result); //I get an array of objects (screenshot included)
                return result; 
            });
        }
    }
});

控制台o / p:

在此處輸入圖片說明

一個對象看起來像這樣:

0: Object
productId: 471744
productName: "xyz"
productViewUrl: "https://someapi.com/us/product/xyz/id471744?uo=4"
imageUrl30: "http://.../source/30x30bb.jpg"
imageUrl60: "http://.../source/60x60bb.jpg"
imageUrl100: "http://.../source/100x100bb.jpg"
collectionId: 700049951
collectionName: "XYZ Collection"
collectionPrice: 9.99
country: "USA"
currency: "USD"
wrapperType: "track"
......
__proto__: Object

因此,我的確在result對象中看到了結果,但仍無法在模板中顯示它。 也許沒有遍歷正確的對象? 還是我需要通過其他內容? 我不知道缺少什么。 感謝您的幫助,我已經堅持了幾個小時。

1)你的路由model鈎子必須返回承諾。

細分您的代碼中正在發生的事情:

export default Ember.Route.extend({
    model: function(params){
        var result = [];              // Create an array
        $.ajax({                      // Start an AJAX request...
          success: function(response){
            result.set('content', response.results);
           }
        });                           // ...but discard the promise
        console.log(result);          // log the array (still empty)
        return result;                // return the array (still empty)
    }
});                                   // much later, the AJAX call completes but
                                      // Ember does not care.

灰燼得到一個空數組。 由於這不是一個承諾,因此它假定可以立即使用它,因此將其設置為model並立即呈現模板。

解決方法:

export default Ember.Route.extend({
    model: function(params){
        var term = 'random';
        var fetchURL = 'http://some-api.com/search?callback=JSON_CALLBACK&limit=10&term='+term;
        return $.ajax({
          url: fetchURL,
          dataType: 'jsonp'
        }).then(function (data) {
            return data.results;   // do whatever processing you have to do
        });
    }
});

這樣,您可以直接將承諾退還給Ember。 看到這一點,Ember知道它必須等待諾言解決。 當AJAX調用成功時,數據將傳遞到then處理程序, then處理程序返回要使用的實際數據。 反過來,Ember獲取該數據並進行設置以供模板使用。

您絕對應該閱讀有關諾言的文章 (請注意,盡管jQuery的“承諾”不是標准的)。

順便說一句,我看到您正在加載ember-data 您絕對應該使用它而不是$.ajax來加載資源。 這就是它的用途,並且在將數據模型簡化為Ember工作流程中做得更好。

2)除非您重寫它,否則model掛鈎返回的數據將在模板中命名為model

因此,只需將results替換為模板中的model ,就可以了: {{#each model as |item|}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM