我有一个简单的木偶ItemView,
import Marionette from 'backbone.marionette';
import Tabs from '@component/tabs/src/js/views/Tabs';
import template from '../../../templates/partials/one/tabs.hbs'
export default Marionette.ItemView.extend({
template,
onRender() {
console.log(document.querySelector('#tabs-main')); //--> null
console.log(this.$('#tabs-main')[0]); // gets appropriate dom element
}
})
与执行此操作相比,document.querySelector为什么返回null。$,我需要执行document.querySelector,因为当我传入id/类时,正在使用的库内部使用它。
发布于 2019-09-25 07:06:25
请参阅https://marionettejs.com/docs/v3.5.1/viewlifecycle.html#view-creation-lifecycle
在onRender中,模板将在内存中呈现(即.$el),但尚未附加到DOM。
如果视图的HTML需要在DOM中,则可以使用onAttached。
请注意,DOM查找比对视图的el进行的查找要慢,因此除非需要对DOM进行查找,否则通常最好在这个.$()查找中使用onRender。
编辑:由于您使用的是ItemView,所以必须使用< v3,下面是用于onAttach的v2文档:https://marionettejs.com/docs/v2.4.7/marionette.view.html#view-attach--onattach-event
第二编辑:添加片段(抱歉,花了一段时间找到老的木偶依赖项)
var MyView = Backbone.Marionette.ItemView.extend({
template: Handlebars.compile('<p id="hello-world">Hello World</p>'),
onRender: function() {
console.log('onRender');
console.log('querySelector', document.querySelector('#hello-world'));
console.log('querySelector equal null?', document.querySelector('#hello-world') === null);
console.log('this.$el', this.$('#hello-world')[0]);
},
onAttach: function() {
console.log('onAttach');
console.log('querySelector', document.querySelector('#hello-world'));
console.log('querySelector equal null?', document.querySelector('#hello-world') === null);
console.log('this.$el', this.$('#hello-world')[0]);
}
});
// ParentView to mock an application
var ParentView = Backbone.Marionette.LayoutView.extend({
el: '.test-container',
template: Handlebars.compile('<div class="my-region"></div>'),
regions: {
myRegion: '.my-region'
},
onRender: function() {
var myView = new MyView();
this.showChildView('myRegion', myView);
}
});
var parentView = new ParentView();
parentView.render();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.3.1/handlebars.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.marionette/2.4.7/backbone.marionette.js"></script>
<div class="test-container"></div>
https://stackoverflow.com/questions/58068906
复制相似问题