gpt4 book ai didi

javascript - Backbone 事件不会使用 Handlebars 模板触发

转载 作者:行者123 更新时间:2023-11-28 02:30:02 24 4
gpt4 key购买 nike

我有这个代码:

PageView.js

var PageView = Backbone.View.extend({
events: {
'click .unpublish': 'unpublish'
},

tagName: 'tr',
className: 'pageedit',

template: Handlebars.compile( PageViewTemplate ),

render: function() {
this.$el.html( this.template( this.model ) );
return this;
},

unpublish: function() {
alert('hi');
}
});

PagesView.js

PagesView = Backbone.View.extend({

tagName: 'tbody',

initialize: function() {
this.collection.on('reset', this.render, this);
this.render();
},

template: Handlebars.compile(PagesTemplate),

render: function() {
var countPages = this.collection.at(0).get('count');

_.each(this.collection.at(0).get('pages'), function(model) {
pageView = new PageView({ model: model });
this.$el.append( pageView.render().el );
}, this);

$('.main').html( this.template({ pages: this.$el.html() }) );

this.delegateEvents(this.events);

return this;
},
});

Page.hbs

<td class="pageId">
{{ id }}
</td>
<td class="pagename">
<a href="/pages/{{ alias }}">{{ pagename }}</a>
</td>
<td class="catname">{{ catname }}</td>
<td class="author">{{ author }}</td>
<td>{{ date }}</td>
<td>
{{#if status}}
<a href="#" class="unpublish">
<img src='../{{ siteURL }}assets/img/admin/published.png'>
</a>
{{else}}
<a href="#" class="publish">
<img src='../{{ siteURL }}assets/img/admin/not-published.png'>
</a>
{{/if}}
</td>
<td>
<a href="#" class="intrash">
<img src='../{{ siteURL }}assets/img/admin/delete.png'>
</a>
</td>

Pages.hbs

<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Catalog</th>
<th>Author</th>
<th>Date</th>
<th>Status</th>
<th>Intrash</th>
</tr>
</thead>
<tbody>
{{{pages}}}
</tbody>
</table>

在router.js中创建所有实例:

var pages = new Pages();
pages.fetch().done(function() {
new PagesView({ collection: pages});
});

如果我单击 .unpublish 链接,PageView 中的事件不会触发。所有 View 都呈现良好,但事件不起作用:(可以帮我?

最佳答案

我认为你的问题就在这里:

$('.main').html( this.template({ pages: this.$el.html() }) );

一旦您说出 this.$el.html(),您就会丢失事件。 Backbone 绑定(bind)delegate (或其等效的 on )到 View 的 el 来进行事件处理,以便事件处理绑定(bind)到 DOM 节点对象。当您说 this.$el.html() 时,您已将所有内容转换为字符串,并且该字符串将进入 DOM;但事件绑定(bind)到 DOM 元素对象而不是字符串。结果是一切看起来都正确,但没有事件触发。

您的Pages.hbs应该看起来更像这样:

<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Catalog</th>
<th>Author</th>
<th>Date</th>
<th>Status</th>
<th>Intrash</th>
</tr>
</thead>
</table>

然后你应该做这样的事情来获取页面上的所有内容:

// Add the basic <table> HTML.
$('.main').html(this.template());
// Append the <tbody> DOM node which has event handling attached to it.
$('.main').find('table.table').append(this.$el);

关于javascript - Backbone 事件不会使用 Handlebars 模板触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14365652/

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