我是 backbonejs 的新手。我正在尝试将正确的 this
对象传递给回调函数,其中该函数是 View 的一种方法。
我目前的解决方案:
APP.LocationFormView = APP.View.extend({
initialize: function () {
if (navigator.geolocation) {
var that = this;
var success = function(position) {
_.bind(that.onSuccessUpdatePos, that, position)();
};
var error = function(error) {
_.bind(that.onFailUpdatePos, that, error)();
}
navigator.geolocation.getCurrentPosition(success,
error);
} else {
}
},
onSuccessUpdatePos: function(position) {
// We can access "this" now
},
onFailUpdatePos : function(error) {
// We can access "this" now
}
});
这是实现我想要的目标的正确方法吗? 有没有更简洁的解决方案?
最佳答案
这就是我要做的。 bindAll
的一个好处是,如果您向 LocationFormView
添加额外的功能,它们将自动绑定(bind) this
。
APP.LocationFormView = APP.View.extend({
initialize: function () {
_.bindAll(this);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(this.onSuccessUpdatePos,
this.onFailUpdatePos);
} else {
}
},
onSuccessUpdatePos: function(position) {
// We can access "this" now
},
onFailUpdatePos : function(error) {
// We can access "this" now
}
});
关于javascript - 有没有更好的方法将 "this"对象传递给回调函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9493657/