Display map from promise with emberJS and handlebars

huangapple go评论76阅读模式
英文:

Display map from promise with emberJS and handlebars

问题

我目前正在努力在emberJS/handlebars中显示地图(这对我来说是新的)。

在服务器端,我有一个command.go文件,其中包含以下内容:

var Actions = map[string]string{
    "EAT": "EAT.",
    "DRINK": "DRNK",
    "SLEEP": "SLP."
}
var Keys = map[string]int{
    "KEY_q": 0,
    "KEY_w": 1,
    "KEY_e": 2,
    ...
}

每个动作和键都有一个字符串常量标识符,并与一个字符串或整数代码相关联。

我想显示一个两列的表格,其中:

  • 第一列显示动作(如吃饭、喝水、睡觉等)
  • 第二列显示一个下拉列表,其中包含可用的键盘键(如Q、W、E等),它们的整数代码是

我有一个控制器将这些映射返回为JSON对象:

ctx.JSON(http.StatusOK, gin.H{
    "actions": models.Actions,
    "keys": models.Keys,
})

然后我有一个emberJS服务,config.js,如下所示:

commands: computed(function () {
    return this.get('ajax').request('<address>/command').then(result => {
        return result;
    });
}),
commandActions: computed('commands', function() {
    return this.get('commands').then((commands) => {
        return commands.actions;
    });
}),
commandKeys: computed('commands', function() {
    return this.get('commands').then((commands) => {
        return commands.keys;
    });
}),

控制器commands.js如下所示:

import Ember from 'ember';

const { computed, inject: { service } } = Ember;

export default Ember.Controller.extend({
    config: service(),

    selectedKey: '',

    actions: {
        selectKey(value) {

        },
    }
});

最后,在commands.hbs中我有:

<div class="table-responsive">
  <table class="table">
    <thead>
      <tr>
        <th>Actions</th>
        <th>Associated key</th>
      </tr>
    </thead>
    <tbody>
      {{#each-in config.commandActions as |key value|}}
        <tr>
          <td>{{command}}</td>
          <td>
            {{#power-select
            options=config.commandKeys
            selected=selectedKey
            allowClear=false
            searchEnabled=false
            onchange=(action "selectKey")
            as |key|
            }}
              {{key}}
            {{/power-select}}
          </td>
        </tr>
      {{/each-in}}
    </tbody>
  </table>
</div>

但是什么都没有显示 :(。
服务运行良好,但在hbs文件中没有显示任何内容。我尝试了不同的each或each-in组合,但没有成功。

有人可以帮忙吗?
我需要在控制器中设置变量,然后在hbs中使用这些变量吗?

我正在使用ember 2.5。

提前感谢

编辑

问题可能是因为我尝试在解决之前显示一个promise对象。对此有什么想法吗?

英文:

I am currently struggling to display maps in emberJS/handlebars (which is new for me).

Server side, I have a command.go file with:

var Actions = map[string]string{
    &quot;EAT&quot;: &quot;EAT.&quot;,
    &quot;DRINK&quot;: &quot;DRNK&quot;,
    &quot;SLEEP&quot;: &quot;SLP.&quot;
}
var Keys = map[string]int{
    &quot;KEY_q&quot;: 0,
    &quot;KEY_w&quot;: 1,
    &quot;KEY_e&quot;: 2,
    ...
}

Each action and key have a string constant identifier and are associated to a string or int code.

I would like to display a 2 columns table in which:

  • column 1 shows actions (like eat, drink, sleep, ...)
  • column 2 shows a dropdown list with available keyboard keys (like Q, W, E, ...), their int code being the id of the <option> tag

I have a controller returning these maps as JSON object:

ctx.JSON(http.StatusOK, gin.H{
	&quot;actions&quot;:      models.Actions,
	&quot;keys&quot;: models.Keys,
})

Then I a an emberJS service, config.js, as follows:

commands: computed(function () {
	return this.get(&#39;ajax&#39;).request(&#39;&lt;address&gt;/command&#39;).then(result =&gt; {
		return result;
	});
}),
commandActions: computed(&#39;commands&#39;, function() {
	return this.get(&#39;commands&#39;).then((commands) =&gt; {
		return commands.actions;
	});
}),
commandKeys: computed(&#39;commands&#39;, function() {
	return this.get(&#39;commands&#39;).then((commands) =&gt; {
		return commands.keys;
	});
}),

The controller commands.js is as follows:

import Ember from &#39;ember&#39;;

const { computed, inject: { service } } = Ember;

export default Ember.Controller.extend({
    config: service(),

    selectedKey: &#39;&#39;,

    actions: {
	    selectKey(value) {

	    },
    }
});

And finally in commands.hbs I have

&lt;div class=&quot;table-responsive&quot;&gt;
  &lt;table class=&quot;table&quot;&gt;
    &lt;thead&gt;
      &lt;tr&gt;
        &lt;th&gt;Actions&lt;/th&gt;
        &lt;th&gt;Associated key&lt;/th&gt;
      &lt;/tr&gt;
    &lt;/thead&gt;
    &lt;tbody&gt;
      {{#each-in config.commandActions as |key value|}}
        &lt;tr&gt;
          &lt;td&gt;{{command}}&lt;/td&gt;
          &lt;td&gt;
            {{#power-select
            options=config.commandKeys
            selected=selectedKey
            allowClear=false
            searchEnabled=false
            onchange=(action &quot;selectKey&quot;)
            as |key|
            }}
              {{key}}
            {{/power-select}}
          &lt;/td&gt;
        &lt;/tr&gt;
      {{/each-in}}
    &lt;/tbody&gt;
  &lt;/table&gt;
&lt;/div&gt;

But nothing is displayed :(.
The service works well but then in the hbs file nothing appears. I have tried different combinations of each or each-in with no success.

Could someone please help?
Do I need to set variables in the controller somehow then use those variables in the hbs?

I'm using ember 2.5.

Thanks in advance

EDIT

The problem may come from the fact that I am trying to display a promise object before it is resolved. Any idea about that?

答案1

得分: 0

我认为使用Ember Concurrency,你的服务将会在Promise解析之前暂停,然后返回你想要的结果,而不是一个#each不知道如何迭代的Promise对象。

你的服务代码将会变成这样:

commands: task(function*() {
  const allCommands = yield this.get('ajax').request('<address>/command');
  return allCommands;
}),
commandActions: computed.alias('commands.actions'),
commandKeys: computed.alias('commands.commandKeys')

然后你的模板将会恢复正常。

英文:

I think with Ember Concurrency, your service will pause until your promise resolves, then return the results you want, rather than a promise object that #each doesn't know how to iterate over.

Your service code would end up looking like this:

commands: task(function*() {
  const allCommands = yield this.get(&#39;ajax&#39;).request(&#39;&lt;address&gt;/command&#39;);
  return allCommands;
}),
commandActions: computed.alias(&#39;commands.actions&#39;),
commandKeys: computed.alias(&#39;commands.commandKeys&#39;)

and your template would be happy again.

答案2

得分: 0

非常感谢你们提供的帮助。

我们最终通过以下方式成功获取到我们想要的结果:

在config.js服务中:

commands: computed(function () {
    return this.get('ajax').request('<address>/command').then(result => {
        return result;
    });
}),

在command.js控制器中:

import DS from 'ember-data';

actions: computed(function() {
    return DS.PromiseArray.create({
        promise: this.get('config.commands').then((allCommands) => {
            let result = [];
            let actions = allCommands['actions'];

            for (var name in actions) {
                let cmd = Ember.Object.create({
                    'name': name,
                    'code': actions[name],
                });

                result.pushObject(cmd);
            }

            return result;
        })
    });
}),

获取键的代码相同。

在commands.hbs中:

<tbody>
  {{#each actions as |action|}}
    <tr>
      <td>{{action.name}}</td>
      <td>
        {{#power-select
          options=keys
          selected=selectedKey
          allowClear=false
          onchange=(action 'selectKey' action)
          searchEnabled=false
          as |key|
        }}
          {{key.name}}
        {{/power-select}}
      </td>
    </tr>
  {{/each}}
</tbody>

再次感谢。

英文:

Thank you all for the help you provided.

We finally managed to get what we wanted by doing the following:

In config.js service:

commands: computed(function () {
    return this.get(&#39;ajax&#39;).request(&#39;&lt;address&gt;/command&#39;).then(result =&gt; {
        return result;
	});
}),

In command.js controller:

import DS from &#39;ember-data&#39;;

actions: computed(function() {
	return DS.PromiseArray.create({
		promise: this.get(&#39;config.commands&#39;).then((allCommands) =&gt; {
			let result = [];
			let actions = allCommands[&#39;actions&#39;];

			for (var name in actions) {
				let cmd = Ember.Object.create({
					&#39;name&#39;: name,
					&#39;code&#39;: actions[name],
				});

				result.pushObject(cmd);
			}

			return result;
		})
	});
}),

Same code to get keys.

And in commands.hbs:

&lt;tbody&gt;
  {{#each actions as |action|}}
    &lt;tr&gt;
      &lt;td&gt;{{action.name}}&lt;/td&gt;
      &lt;td&gt;
        {{#power-select
          options=keys
          selected=selectedKey
          allowClear=false
          onchange=(action &#39;selectKey&#39; action)
          searchEnabled=false
          as |key|
        }}
          {{key.name}}
        {{/power-select}}
      &lt;/td&gt;
    &lt;/tr&gt;
  {{/each}}
&lt;/tbody&gt;

Thanks again

huangapple
  • 本文由 发表于 2017年2月8日 21:01:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/42113898.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定