问题描述
我正在研究将Ember与现有的Rails应用程序集成,以利用Ember的绑定,事件(didInsertElement等)...
I'm looking into integrating Ember with an existing Rails application, to take advantage of Ember's bindings, events (didInsertElement, etc.) ...
现在我不想将我的erb视图转移到句柄,而是我想创建Ember View对象并将它们附加到DOM中的各种元素。例如,我可能有
Now I don't want to transfer my erb views to handlebars, but instead I want to create Ember View objects and attach them to various elements already in the DOM. For example, I might have
<html>
<body>
<div class="header">
</div>
<div class="content">
</div>
<div class="footer">
</div>
</body>
</html>
和(在DOM上准备好)为每个元素创建一个视图:
and (on DOM ready) create a View for each element:
App.HeaderView = Ember.View.create({
// capture $('.header') to this
// console.log(this.$().attr('class')) should then output `header`
});
推荐答案
确定以下作品,但我还没有完全测试
Ok the following works but I haven't fully tested it.
灵感来自于@ pangratz的我使用以下方法扩展 Ember.View
Inspired by @pangratz's pull request I extend Ember.View
with the following method for
Ember.View = Ember.Object.extend(
/** @scope Ember.View.prototype */ {
// ........
wrap: function(target) {
this._insertElementLater(function() {
// Set all attributes name/values from target
var target_attrs = {};
var $this = this.$();
for (var attr, i=0, attrs=$(target)[0].attributes, l=attrs.length; i<l; i++){
attr = attrs.item(i)
var attrName = attr.nodeName;
var attrValue = attr.nodeValue;
if(attrName === 'id') continue;
$this.attr(attrName, attrValue);
}
// Set HTML from target
$this.html($(target).html());
Ember.$(target).replaceWith($this);
});
return this;
},
// ........
});
基本上它复制目标元素的html内容及其属性。然后只需要执行
Basically it copies the html content of the target element as well as its attributes. Then by just doing
App.HeaderView = Ember.View.create().wrap('.header');
.header
元素在DOM中)现在在App.HeaderView中。
the .header
element (that is already in the DOM) is now in App.HeaderView.
请参阅
这篇关于从jQuery对象创建Ember View的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!