javascript - EmberJS 使用 View 处理 DOM 事件

标签 javascript jquery json view ember.js

我想使用 View 切换单个表单(见下图)。 当我添加新的表单集时,我的代码基本上可以工作,它会向 json 添加一个空括号,然后我 使用eachloop打印json

查看模板

{{#each view.anotherField}}

<div class="panel panel-default">
     {{action 'toggleView' 'toggleViews' target='view'}}
        ...
</div>       
{{#unless view.toggleViews}}
...content to toggle...
{{/unless}}

View Controller ??

actions: {
    showMoreFields: function(){
      this.get('anotherField').pushObject({name: ''});

toggleView: function(param){
      this.toggleProperty(param);
    }

enter image description here

在这张给定的图片中,您可以看到我已将组织 View 切换为事实,我想要的是仅切换单击的部分而不是所有表单。有解决办法吗?

干杯,

克里斯蒂安

最佳答案

如果我理解正确,您需要处理 View 的特定部分/表单的事件。要实现这一目标,至少有三种方法,

1。使用 {{action}} 帮助器传递要修改的对象。然后在您的函数中修改该对象的属性并将其反射(reflect)在您的模板中,例如切换表格。也许在你的情况下它可能是这样的,

....
{{#each field in view.anotherField}}

<div class="panel panel-default">
     {{action 'toggleView' field target='view'}}
....

2.创建一个 subview /模板(例如 SubFormView)来容纳每个表单并处理该 View 中的切换事件。然后通过主视图模板中的 {{view}} 帮助器包含此内容。

3。使用纯 js DOM 处理(无 {{action}} 帮助程序)并从那里调用您的 ember 组件。

方法 1 和 3 的示例可以在此处找到, http://emberjs.jsbin.com/acUCocu/1

hbs

<script type="text/x-handlebars" data-template-name="index">
    <i>using <b>&#123;&#123;action&#125;&#125;</b> helper</i>
    <ul>
    {{#each color in model}}
      <li {{action 'test' color}}>{{color.name}}</li>
    {{/each}}
    </ul>

    <i>using pure js DOM event handling</i>
    <ul>
    {{#each color in model}}
      <li onclick="Ember.View.views[$(this).closest('.ember-view').attr('id')].controller.send('test2',this)">{{color.name}}</li>
    {{/each}}
    </ul>
  </script>

js

App = Ember.Application.create();

App.Router.map(function() {
  // put your routes here
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return colors;
  },
  actions:{
    test:function(param){
      alert('this is color:'+param.get('name')+" ("+param+")");
    },
    test2:function(elem){
      alert('from pure js, clicked element: '+elem);
      $(elem).css('color','red');
    }
  }
});

App.Color = Ember.Object.extend({
  name:null
});

var colors=[];
colors.pushObject(App.Color.create({name:'red'}));
colors.pushObject(App.Color.create({name:'green'}));
colors.pushObject(App.Color.create({name:'blue'}));

关于javascript - EmberJS 使用 View 处理 DOM 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20856812/

相关文章:

javascript - 我怎么能用javascript写这个短函数?

javascript - 使用 css jquery 设置背景图像

java - 无法导入 Json 处理类

json - 在powershell中用空字符串键解析json

php - 安卓、PHP、HttpGet

javascript - 双单选按钮选择错误 AngularJs

javascript - 如何使用 jQuery 比较 tr 中的几个 td.text()

javascript - 如何在基于单选按钮的 onClick 事件中添加 if-else 语句

javascript - 如何将 char 添加到 javascript 对象键和值?

javascript - jQuery IE9-10 : unable to get property replace of undefined or null reference