简体   繁体   English

Ember.js-获取DOM元素的模型数据

[英]Ember.js - get the model data of a DOM element

I have a DOM element and want to get the data model that it is bound to. 我有一个DOM元素,想要获取绑定到的数据模型。

This has to be done outside of any ember controller / component. 这必须在任何余烬控制器/组件之外完成。 All I have to work with is the DOM element and the global Ember variable (because this piece of code runs from an externally loaded script file). 我需要使用的只是DOM元素和全局Ember变量(因为这段代码是从外部加载的脚本文件运行的)。

How can this be done? 如何才能做到这一点?

It can't be done (not out of the box anyway). 它无法完成(无论如何也不是开箱即用的)。 There is no relationship between DOM elements and models. DOM元素和模型之间没有关系。 The best way I could think of doing this would be to bind the ID of the model to and attribute on a particular DOM item. 我想到的最好的方法是将模型的ID绑定到特定的DOM项目并赋予其属性。 For example: 例如:

export default Ember.Component.extend({
    model: null,
    attributeBindings: ['data-model-id'],
    'data-model-id': function() {
        return this.get('model.typeKey') + ':' + this.get('model.id');
    }.property('model.{typeKey,id}');
});

Then you'd get an element in the DOM like this: 然后,您将在DOM中获得如下所示的元素:

<div id="ember189" data-model-id="user:86">...</div>

But this only works if your HTML is written such that each model gets its own DOM element. 但这仅在编写HTML时使每个模型都有自己的DOM元素时才有效。 And you'd still have to access private API to get the store via App.__container__.lookup() . 而且,您仍然必须访问私有API才能通过App.__container__.lookup()获得商店。

Unless you feel like you have a really good reason to do something like this, I would avoid it. 除非你觉得你有一个很好的理由做这样的事情,我会避免。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM