获取对为给定模型对象创建的EmberJS视图的引用? [英] Get references to EmberJS views created for a given model object?

查看:58
本文介绍了获取对为给定模型对象创建的EmberJS视图的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个 DefinedWord 对象的列表,每个对象都在 {{#each}} 中呈现阻止为页面底部的 DefinedWordView div列表。

Say I have a list of DefinedWord objects, which are each rendered in an {{#each}} block as a list of DefinedWordView divs at the bottom of the page.

当用户单击一个单词时,我查找关联的 DefinedWord 。现在,我想引用为此 DefinedWord 呈现的 DefinedWordView ,因此我可以 ScrollTo( ) DefinedWordView 的div。

When a user clicks a word, I lookup the associated DefinedWord. Now I want a reference to the DefinedWordView rendered for this DefinedWord, so I can ScrollTo() the DefinedWordView's div.

我总是可以给每个视图盖章加载时带有反向引用的模型对象,但这看起来有点难看。没什么大不了的,但是我认为我需要在许多其他操作中做到这一点,我宁愿不要在模型对象中添加对视图的反向引用。

I can always have the views stamp each model object with a back-reference when they load, but it seems a little ugly. Not a big deal, but I think I'll need to do this for lots of other operations, and I'd rather not litter my model objects with back-references to views.

有人建议使用 ember-y 惯用法来解决这个问题吗?也许 EmberJS 需要标准的单视图注册表 还是什么?

Anyone have suggestions for an ember-y idiom to handle this? Maybe EmberJS needs a standard "singleton view registry" or something?

推荐答案

使模型使用 Em.Evented mixin:

Make your model use the Em.Evented mixin:

App.Word = Em.Object.extend(Em.Evented, {
  // ...
});

单击模型后,触发其上的事件,我们称其为选定

When your model is clicked, trigger an event on it, let's call it selected.

App.WordView = Em.View.extend({
  click: function () {
    // content == the model
    this.get('content').trigger('selected');
  }
})

模型的视图可以绑定到该事件,并在触发该事件时滚动到自身:

The model's view can bind to that event and when it's fired, scroll to itself:

// just pseudo code:
App.DefinedWordView = Em.View.extend({
  init: function () {
    this._super();

    //listen for the 'selected' event and call 'scrollToDefinition' on 'this'
    this.get('content').on('selected', this, 'scrollToDefinition');
  },

  scrollToDefinition: function () {
    $(document).scrollTo( this.$() );
  }
})

这篇关于获取对为给定模型对象创建的EmberJS视图的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆