我有一个愚蠢的问题,我唯一的解决方案是一个草率的黑客,现在给我其他问题。
或阅读此处的代码:
<input id='1' value='input1' />
<template id='template1'>
<input id='2' value='input2' />
</template>
// Declare an ItemView, a simple input template.
var Input2 = Marionette.ItemView.extend({
template: '#template1',
onRender: function () {
console.log('hi');
},
ui: { input2: '#2' },
onRender: function () {
var self = this;
// Despite not being in the DOM yet, you can reference
// the input, through the 'this' command, as the
// input is a logical child of the ItemView.
this.ui.input2.val('this works');
// However, you can not call focus(), as it
// must be part of the DOM.
this.ui.input2.focus();
// So, I have had to resort to this hack, which
// TOTALLY SUCKS.
setTimeout(function(){
self.ui.input2.focus();
self.ui.input2.val('Now it focused. Dammit');
}, 1000)
},
})
// To start, we focus input 1. This works.
$('#1').focus();
// Now, we make input 2.
var input2 = new Input2();
// Now we 1. render, (2. onRender is called), 3. append it to the DOM.
$(document.body).append(input2.render().el);
正如我们可以看到的,我的问题是,在呈现(onRender
)之后,我无法将View调用焦点放在自身上,因为它尚未附加到DOM。据我所知,没有其他事件被称为onAppend
,这可以让我检测它何时被实际附加到DOM。
我不想从ItemView外部调用焦点。为了我的目的,必须从内部完成。
有什么好主意吗?
事实证明,对于Marionette.js中的所有DOM追加调用onShow()
,无论是CollectionView,CompositeView还是Region,都不在文档中!
感谢一百万,lukaszfiszer。
答案 0 :(得分:3)
解决方案是在ItemView
内呈现Marionette.Region
。这样,一旦将onShow
方法插入DOM,就会在视图上调用<input id='1' value='input1' />
<div id="inputRegion"></div>
<template id='template1'>
<input id='2' value='input2' />
</template>
方法。
示例:
(...)
onShow: function () {
this.ui.input2.val('this works');
this.ui.input2.focus();
},
(...)
$('#1').focus();
var inputRegion = new Backbone.Marionette.Region({
el: "#inputRegion"
});
var input2 = new Input2();
inputRegion.show(input2);
{{1}}
Marionette docs中的更多信息:https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.region.md#region-events-and-callbacks
答案 1 :(得分:1)
好吧,我设法通过扩展Marionette.js来解决它,但如果其他人有更好的想法,不涉及扩展库,我会 GLADLY 接受它并给你买一个甜甜圈
// After studying Marionette.js' annotated source code,
// I found these three functions are the only places
// where a view is appended after rendering. Extending
// these by adding an onAppend call to the end of
// each lets me focus and do other DOM manipulation in
// the ItemView or Region, once I am certain it is in
// the DOM.
_.extend(Marionette.CollectionView.prototype, {
appendHtml: function(collectionView, itemView, index){
collectionView.$el.append(itemView.el);
if (itemView.onAppend) { itemView.onAppend() }
},
});
_.extend(Marionette.CompositeView.prototype, {
appendHtml: function(cv, iv, index){
var $container = this.getItemViewContainer(cv);
$container.append(iv.el);
if (itemView.onAppend) { itemView.onAppend() }
},
});
_.extend(Marionette.Region.prototype, {
open: function(view){
this.$el.empty().append(view.el);
if (view.onAppend) { view.onAppend() }
},
});