Backbonejs,视图中的行为,未捕获的类型错误
Backbonejs, behavior of this in a View, Uncaught TypeError
是否已解决?不完全是。
https://github.com/jashkenas/backbone/issues/2822
这是一款Cordova+Backbone移动应用程序。一段时间以来,我一直在用头撞这个,觉得是时候寻求帮助了。
App.PhotoButtonView = Backbone.View.extend({
pic: "",
picid: 1,
events : {
"click #addPhotoBtn": "addPhoto"
},
initialize: function( options ) {
this.options = options;
},
render: function() {
var html = JST['photo-button/view']({num: this.options.picid});
$(this.el).html( html );
setTimeout(this.postrender, 0);
return this;
},
postrender: function() {
// reset to default image pic
console.log('addPhotoBtn' + this.options.picid);
document.getElementById('addPhotoBtn' + this.options.picid ).src = this.pic;
var photo = document.querySelector("#addPhotoBtn" + this.options.picid);
},
我还是。。。
错误:未捕获类型错误:无法读取未定义的属性"picid"
但现在它被postrender函数触发了。我打赌这与setTimeout破解有关。
编辑:这是父视图中初始化PhotoButtonView 的代码
postrender: function() {
$('#submitBtn, .topcoat-button--large').prop('disabled', false);
this.photo = new App.PhotoButtonView({picid: 1});
$('#photoButtons').html(this.photo.render().el);
if (App.activePost.get('photo1')) {
this.photo2 = new App.PhotoButtonView({picid: 2});
$('#photoButtons').append(this.photo2.render().el);
}
if (App.activePost.get('photo2')) {
this.photo3 = new App.PhotoButtonView({picid: 3});
$('#photoButtons').append(this.photo3.render().el);
}
if (App.activePost.get('photo3')){
this.photo4 = new App.PhotoButtonView({picid: 4});
$('#photoButtons').append(this.photo4.render().el);
}
},
注:一位大二的CS实习生编写了这个代码库。我正在为新功能打补丁。
这似乎是关于this
绑定的常见错误。
因为我们将未绑定的this.postrender
回调传递给setTimout,所以它将在全局命名空间的范围内被称为"函数"样式,this
将绑定到全局对象,而不是视图。
有两种方法可以调整setTimeout调用,以便在postrender方法中引用this
时正确绑定它。
选项1(调用/应用样式):
setTimeout(this.postrender.bind(this), 0);
选项2(方法风格):
var that = this;
setTimeout(function () {
that.postrender();
}, 0);
这是Yehuda Katz关于this
和调用的一篇非常好的文章。http://yehudakatz.com/2011/08/11/understanding-JavaScript-function-invocation-and-this/
相关文章:
- 为什么会出现错误;未捕获的类型错误:undefined不是函数;
- 同样,同样的错误'ahorcado.js:26未捕获类型错误:无法读取属性'beginPath'
- 未捕获的类型错误:无法读取属性'删除'的未定义
- 未捕获的类型错误:无法读取属性'name'即使它存在,也无法定义
- 看到“;未捕获的类型错误:无法读取属性'weight'未定义的“;尽管按照字面上的指示
- Soundcloud api"未捕获的类型错误:无法读取属性'uri'“未定义”;
- 未捕获的类型错误:无法读取属性'addEventListener'的null chrome扩展名
- 如何解决这种情况下的非法调用类型错误
- 未捕获的类型错误:$(..).dataTable不是函数
- 未捕获的类型错误:无法读取属性'状态'在react中为null
- 未捕获的类型错误:topFrame.window.changeSelectedBarStyle不是函数,原因是什么
- 类型错误:url未定义extjs 4正在填充组合框
- 未捕获的类型错误:无法读取属性'中止'的未定义
- 类型错误'未定义'不是对象(正在评估'navigator.connection.type'
- 未捕获的类型错误:无法设置属性'innerHTML'如果为null,则将脚本移动到正文不会;不起作用
- 未捕获的类型错误:undefined不是函数$
- 输入类型文件的未捕获类型错误
- 未捕获的类型错误:无法设置属性'背景'的未定义
- "未捕获类型错误/丢弃意外“;因为一句台词而出现?(HTML w/<脚本>)
- Javascript未捕获类型错误:无法读取属性'0'的未定义