[英]How to define view Element within a view's method in backbone.js?
在構建視圖以控制可重用的ui控件(選項卡,模式,警報等)時。 我希望能夠調用ui.tabs(options)
,然后將創建視圖“對象”。
我已經設法做到了,我可以打電話給ui.tabs(options)
。 但是現在我還不太清楚如何使用views方法(即: tabs()
)設置元素。 當我將模板設置為this.el
, this.$el
或this.$el.html
我只會得到未定義的錯誤。
有人可以解釋我要去哪里錯嗎?
到目前為止,這是我的代碼(我知道很簡單):
/* UI Tools */
define(
[
"backbone",
"text!templates/ui-tabs.html"
],
function (Backbone, tabsTemplate) {
var uiView = Backbone.View.extend({
events: {
"click .tab": "clickTab"
},
initalize: function () {
},
/*
* TAB CONTROLS
*/
tabs: function (options) {
console.log(options);
console.log(this.$el);
this.el = $(_.template(tabsTemplate, options));
},
clickTab: function () {
console.log('tab clicked');
},
/*
* MODAL CONTROLS
*/
modal: function () {
},
/*
* ALERT CONTROLS
*/
alert: function () {
},
/*
* CORE
*/
render: function () {
return this.$el;
}
});
return new uiView();
}
);
_.template
返回一個函數。 使用返回的函數來呈現模板:
var templateFunc = _.template(tabsTemplate, options); // returns a function
templateFunc({ you: "data" }); // returns a string
el
✘不要這樣設置el
或$el
:
this.el = /* ... */;
✔而是使用this.setElement
來確保正確設置el
和$el
並重新委托事件:
this.setElement(this.template());
在我制作的Backbone應用程序中,我為每個可重用組件創建了一個視圖,而不是為所有組件創建了一個實例。
拆分視圖並在需要時返回構造函數以構建組件。
define([/* ... */], function(/* ... */) {
var ModalView = Backbone.View.extend({
/* ... */
});
return ModalView;
});
並對每個組件執行相同的操作。
然后,在較大的組件(如頁面布局)中,使用許多較小的組件。
define([
'modal-view',
'tabs-view'
], function(ModalView, TabsView) {
var Layout = Backbone.View.extend({
/* ... */
initialize: function(){
this.view = {
modal: new ModalView(),
tabs: new TabsView(),
};
},
});
return Layout;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.