4

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

当用户单击一个单词时,我会查找相关的DefinedWord. 现在我想要一个为此DefinedWordView渲染的参考DefinedWord,所以我可以's div.ScrollTo()DefinedWordView

我总是可以让视图在加载时为每个模型对象添加一个反向引用,但这看起来有点难看。没什么大不了的,但我认为我需要为许多其他操作执行此操作,而且我宁愿不要在我的模型对象中乱扔对视图的反向引用。

任何人有一个ember-y成语来处理这个建议?也许EmberJS需要一个标准的“单一视图注册表”之类的?

4

2 回答 2

2

让你的模型使用Em.Eventedmixin:

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

当你的模型被点击时,触发一个事件,我们称之为selected

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

模型的视图可以绑定到该事件,当它被触发时,滚动到它自己:

// 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.$() );
  }
})
于 2012-11-30T02:24:47.770 回答
1

https://stackoverflow.com/a/13638139/294247很棒,但使用属性来发出信号似乎不合适。我意识到我应该使用从对象调度的事件,并让视图做出适当的反应。

使用 Ember.Evented 混合:

App.DefinedWord = Ember.Object.extend(Ember.Evented, {
    // ...
    scrollToDefinition: function () {
        this.trigger('scrollToDefinition');
    }
});

App.DefinedWordView = Ember.View.extend({
    init: function () {
        this._super();
        this.get('content').on('scrollToDefinition', this, 'scrollToDefinition');
    },
    scrollToDefinition: function () {
        $(document).scrollTo(this.$());
    }
});
于 2012-12-01T22:37:43.880 回答