¿Cómo pasar eventos a una Vista principal, pasando la Vista secundaria que desencadenó el evento?

StackOverflow https://stackoverflow.com/questions/9379345

  •  28-10-2019
  •  | 
  •  

Pregunta

Considere una Vista que define una lista de objetos:

App.ListView = Ember.View({
  items: 'App.FooController.content'

  itemClicked: function(item){

  }
)};

con la plantilla:

<ul>
{{#each items}}
    {{#view App.ItemView itemBinding="this" tagName="li"}}
      <!-- ... -->
    {{/view}}
{{/each}}
</ul>

y el ItemView:

App.ItemView = Ember.View.extend({

  click: function(event){

    var item = this.get('item');

    // I want to call function itemClicked(item) of parentView
    // so that it handles the click event
  }
})

Básicamente, mi pregunta es ¿cómo paso eventos a las vistas principales, especialmente en el caso en que la vista secundaria no conoce la vista principal?Entiendo que puedes conseguir una propiedad. foo de un parentView con cualquiera de los dos this.getPath('parentView').get('foo') o this.getPath('contentView').get('foo').Pero ¿qué pasa con una función (en este caso, itemclicked())?

¿Fue útil?

Solución

this.get('parentView').itemClicked(this.get('item')); debería hacer el truco.

Otros consejos

Puedes usar el {{action}}ayudante, ver: http://jsfiddle.net/smvv5/

Plantilla:

<script type="text/x-handlebars" >
    {{#view App.ListsView}}
        {{#each items}}
            {{#view App.ListView itemBinding="this" }}
                <li {{action "clicked" target="parentView" }} >{{item.text}}</li>
            {{/view}}
        {{/each}}
    {{/view}}
</script>​

JS:

App = Ember.Application.create({});

App.Foo = Ember.ArrayProxy.create({
    content: [Ember.Object.create({
        text: 'hello'
    }), Ember.Object.create({
        text: 'action'
    }), Ember.Object.create({
        text: 'world'
    })]
});
App.ListsView = Ember.View.extend({
    itemsBinding: 'App.Foo',
    clicked: function(view, event, ctx) {
        console.log(Ember.getPath(ctx, 'item.text'));
    }
});
App.ListView = Ember.View.extend({
});​

Versiones recientes de Ember usan el actions Hash en lugar de métodos directamente sobre el objeto (aunque este método desaprobado todavía es compatible, podría no ser por mucho tiempo). Si desea una referencia a la vista pasada al controlador, envíe a través de la "vista" como un parámetro y use el parentView como el objetivo.

<button {{action "onClicked" view target="view.parentView"}}>Click me.</button>

App.ListsView = Ember.View.extend({
    actions: {
        onClicked: function(view) {
        }
    }
});

{{action}} Helper no envía a través del objeto del evento. Todavía no estoy seguro de cómo obtener referencia al evento si lo necesita.

fuente

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top