奇怪的问题绑定事件与骨干,“;这个“;没有更新
Strange issue binding events with backbone, "this" is not being updated
我在处理主干和绑定事件时遇到了一个奇怪的问题。我会看看我是否能清楚地解释它(这是一个裁剪的例子…)
在一个视图中,我在初始化方法中有以下代码
var MyView = Backbone.View.extend({
initialize: function(options) {
//[...]
this.items = [];
this.collection.on('reset', this.updateItems, this);
this.fetched = false;
},
render: function() {
if (!this.fetched) {
this.collection.fetch(); // fetch the collection and fire updateItems
return this;
}
this.$el = $('#my-element');
this.$el.html(this.template(this.items));
},
updateItems: function() {
this.fetched = true;
this.loadItems();
this.render(); // call render with the items array ready to be displayed
}
}
这个想法是,我必须获取集合,处理项目(this.loadItems
),然后设置this.$el
。
我面临的问题是,在updateItems
中,我看不到在绑定(this.collection.on
…)之后添加任何属性
看起来绑定是针对冻结版本的视图进行的。我尝试添加属性来测试它,但在updateItems
内部(如果被集合重置事件触发,则在render内部)我看不到添加的属性。
我在获取集合之前解决了绑定集合的问题,如下所示:
render: function() {
if (!this.fetched) {
this.collection.on('reset', this.updateItems, this);
this.collection.fetch();
return this;
}
但这是一种奇怪的行为。似乎在绑定时,会生成"this"的副本,而不是引用。
我说得对吗?或者我做错了什么?
您应该在集合视图的初始化阶段执行绑定:
// View of collection
initialize: function() {
this.model.bind('reset', this.updateItems);
}
现在,当完成对集合的提取时,将调用updateItems方法。当然,在执行此操作之前,您需要绑定模型和视图:
var list = new ListModel();
var listView = new ListView({model: list});
list.fetch();
相关文章:
- 这个旋钮没有更新;我不知道为什么
- ReactJS-这个状态中的数组在删除时被正确更新,但结果是't,直到以后的状态发生变化
- 为什么这个 JQuery Cookie 值没有更新
- 这个可重用的 AngularJS 服务如何在鼠标移动时更新
- 我收到一个错误:类型错误:在使用解析 API 更新用户对象时未定义 e.changes.如何解决这个问题
- 为什么这个 emberjs 模板不更新
- Javascript singleton,如何更新这个变量
- 我怎样才能让这个计时器实时更新(Javascript)
- 为什么这个角值没有更新
- Jquery AJAX -更新文本跨度时,这个按钮被点击
- 为什么这个angular指令不更新?
- 为什么这个html没有使用jQuery进行更新
- 只有一些我的解析对象更新(总是9,但没有更多),当我运行这个javascript解析云代码
- 为什么不更新这个元素的宽度?JQuery
- 这个网页是如何更新的?萤火虫显示没有网络活动
- 我如何让背景颜色自动更新与这个javascript
- 为什么这个D3.js柱状图上的数据没有正确更新
- 奇怪的问题绑定事件与骨干,“;这个“;没有更新
- 这个代码是如何在没有弹出和推送的情况下反转和更新的
- 猫鼬模式方法和“这个”更新属性 - NodeJS