2017-02-07 20 views
1

我創建了一個簡單視圖,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

回答

1

選項重寫視圖的屬性

並非所有的選項都自動覆蓋在實例化時傳遞的視圖類屬性。

ui看起來不是其中之一。

骨幹將在視圖自動應用以下(私人)viewOptions

// List of view options to be set as properties. 
var viewOptions = [ 
    'model', 
    'collection', 
    'el', 
    'id', 
    'attributes', 
    'className', 
    'tagName', 
    'events' 
]; 

在視圖構造,this與所選擇的選項(source)擴展:

_.extend(this, _.pick(options, viewOptions)); 

如何通過ui選項?

您或者需要將ui散列放入視圖類定義中,或者自己應用UI散列。

var MyView = Marionette.ItemView.extend({ 
    template: "#my-template", 
    initialize: function(options) { 

     // merge the received options with the default `ui` of this view. 
     this.ui = _.extend({}, this.ui, this.options.ui); 
    } 
}); 

請注意,傳遞給視圖的選項是available in this.options automatically


這背後的真正目標是什麼?

如果你打算用和events來調用它的回調,最好是定義一個新的視圖。

它看起來像一個XY problem其中真正的問題在於應用程序的架構,但我們不能幫助,因爲你問什麼阻止你現在。

相關問題