我如何得到点击元素模型在视图-余烬

How do I get clicked elements model in View - Ember

本文关键字:模型 视图 余烬 元素 何得      更新时间:2023-09-26

我有一个视图与行数的div。当我点击一个div时,当前被点击的元素应该被选中。下面是我使用的代码:

{{#each}} 
    <div {{action target="view" on="click" allowedKeys="shift"}} {{bind-attr class=':user isActive'}} > 
        {{test}}
    </div>
{{/each}}

我的视图是由一个模型支持的:

model: function() { 
    return [{'test':'1'}, {'test' :'2'}, {'test': '3'}, {'test': '4'}]; 
}

在我的视图中,我处理了点击处理程序。

click: function( e ) { 
    if( e.shiftKey ){
        this.modelFor("index").send('changeBgSelection', {'test' :'2'} ); // Here I could not get the current clicked elements model.
    }
    // Here I need to get the current clicked elements model. When I click the second element I need to get as  "{'test' :'2'}". But I could not get the current elements model. Instead I can get the whole model.
}

在我的路由中,在这里,被点击的元素被激活。

actions:{
    changeBgSelection: function (params) { 
        var select = this.get("controller").objectAt(this.modelFor("index").indexOf(params)); 
        select.set('isActive', true)
    }
}

那么我如何在视图中获得当前被点击的元素模型呢?这样我就可以将模型传递给我的Route,使被点击的div活动,并按下Shift键。

编辑:Jsbin Link

在Ember中有两种方式响应鼠标点击:

  • 调用动作
  • 在视图中处理

似乎你试图把两者结合起来,结果弄得一团糟。我肯定有办法让它起作用,但我找不到。请允许我提出一个替代方案。

一般来说,如果javascript或事件处理(如示例中的SHIFT键)发生了一些奇特的事情,我喜欢在本地化视图中处理它。在这里,每个'TestView'都绑定到一个单独的模型实例,并根据用户输入对其进行操作。

  <script type="text/x-handlebars" data-template-name="index">
    {{#each}}
      {{#view App.TestView content=this}}
        {{this.test}}
      {{/view}}
    {{/each}}
  </script>
App = Ember.Application.create();
function wrap(ob) {
  return Ember.Object.create(ob);
}
App.IndexRoute = Ember.Route.extend({
  model: function() {
    return [
      wrap({'test':'1', 'isActive':false}),
      wrap({'test' :'2', 'isActive':false}),
      wrap({'test': '3', 'isActive':false}),
      wrap({'test': '4', 'isActive':false})
    ];
  }
});
App.TestView = Ember.View.extend({
  classNames: ["user"],
  classNameBindings: ["content.isActive:is-active"],
  click: function(e) { 
    if (e.shiftKey) {
      this.get("content").toggleProperty("isActive");
    }
  }
});

这个可以再清理一些,但是您得到了要点。