[英]Backbone.js events on templates
I am trying to assign a event to a button using backbones events: . 我正在尝试使用骨干事件将事件分配给按钮:。 I gave it a try how all the tuts done it but nothing has worked so far.
我试一试了所有的tuts是如何做到的,但到目前为止还没有任何工作。 My suspicion is that I can't add events because the content of $el hasnt been updated yet (I load in a template useing underscore).
我怀疑是我无法添加事件,因为$ el的内容尚未更新(我加载了一个使用下划线的模板)。 So my question would be how can I assign events to classes which arent loaded in at the start?
所以我的问题是如何将事件分配给一开始没有加载的类?
My code is on Github in the repo https://github.com/PITS/bluLime-CMS 我的代码在回购https://github.com/PITS/bluLime-CMS上的Github上
The file I am working on is located under ui/scripts/views/UserPage.js. 我正在处理的文件位于ui / scripts / views / UserPage.js下。
var UserView = Backbone.View.extend({
initialize: function() {},
render: function() {
var data = {
};
var compiled = _.template(UserPage, data);
$.when($('.main').html(compiled)).then(function() {
this.$el = $(".userEdit");
console.log(this.$el);
});
},
events: {
"click .header button": "openPreview"
},
openPreview: function() {
alert("HI");
}
The Template is located in ui/scripts/views/templates/UserPage.js 模板位于ui / scripts / views / templates / UserPage.js中
<div class="userEdit">
<div class="header">
<h2>
Edit Users
</h2>
<button>
</button>
</div>
</div>
PS: I have already tryed to solve the problem but I failed PS:我已经尝试解决问题,但我失败了
Your events aren't being delegated to the correct element after you change this.$el
. 更改后,您的活动不会被委托给正确的元素
this.$el
。 Instead of directly setting this.$el
, use View.setElement
. 而不是直接设置
this.$el
,而是使用View.setElement
。 It will deal with event re-delegation for you. 它将为您处理事件重新授权。
Also, you'll need to create a view
variable to keep the reference to this
, since the context inside the then
callback is no longer the view. 此外,您需要创建一个
view
变量来保持this
的引用,因为then
回调内的上下文不再是视图。
Your render function should look like this: 您的渲染功能应如下所示:
render: function() {
var data = {
};
var compiled = _.template(UserPage, data);
var view = this;
$.when($('.main').html(compiled)).then(function() {
view.setElement($(".userEdit"));
console.log(view.$el);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.