我創建了一個簡單視圖,MyView
,從ItemView
延伸。然後,當我創建MyView
的實例時,我試圖添加對視圖中UI元素的引用以及使用這些UI元素的事件。使用Backbone.Marionette,爲什麼我在創建視圖的新實例時不能引用@ui元素?
HTML
<div id="container"></div>
<script type="text/template" id="my-template">
<p>This is a rendered template.</p>
<button data-ui="changeModelNameButton">Change Model Name</button>
</script>
JS
// Define a custom view that extends off of ItemView
var MyView = Marionette.ItemView.extend({
template: "#my-template"
});
// Instantiate the custom view we defined above
var view = new MyView({
el: "#container",
ui: {
changeModelNameButton: '[data-ui~=changeModelNameButton]'
},
events: {
'click @ui.changeModelNameButton': function() {
alert('here');
}
}
});
// Render the view in the element defined within the custom view instantiation method
view.render();
我在控制檯收到以下錯誤:
Uncaught TypeError: Cannot read property 'changeModelNameButton' of undefined
我注意到,如果我將ui聲明移動到視圖定義中,它可以正常工作,但我想知道爲什麼我在創建實例時無法添加這些聲明。有沒有辦法將它們添加到實例或我錯過了什麼?
注:我使用的骨幹1.3.3,2.4.4木偶,下劃線1.8.3和jQuery 3.1.1