gpt4 book ai didi

javascript - 如何在backbone.js中的 View 方法中定义 View 元素?

转载 作者:行者123 更新时间:2023-12-03 05:25:48 24 4
gpt4 key购买 nike

构建 View 来控制可重用的 ui 控件(选项卡、模式、警报等)。我希望能够调用 ui.tabs(options) ,然后它将创建 View “对象”。

我已经成功地可以调用ui.tabs(options)。但现在我不太清楚如何使用 View 方法(即:tabs())设置元素。当我将模板设置为 this.elthis.$elthis.$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();
}
);

最佳答案

使用 Underscore 的模板

_.template 返回一个函数。使用返回的函数渲染模板:

var templateFunc = _.template(tabsTemplate, options); // returns a function
templateFunc({ you: "data" }); // returns a string

Additional information

更改el

✘ 不要像这样设置 el$el:

this.el = /* ... */;

✔ 相反,请使用 this.setElement 确保 el$el 均设置正确并重新委托(delegate)事件:

this.setElement(this.template());

制作可重用组件

在我制作的 Backbone 应用程序中,我为每个可重用组件创建了一个 View ,而不是为所有组件创建了一个实例。

Split View并返回构造函数以在需要时构建组件。

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;
});

关于javascript - 如何在backbone.js中的 View 方法中定义 View 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41148763/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com