jxu*_*jxu 2 javascript backbone.js
我是backbonejs的新手.我试图将正确的this对象传递给回调函数,其中该函数是视图的方法.
我目前的解决方案
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
}
});
Run Code Online (Sandbox Code Playgroud)
这是实现我想要的正确方法吗?对此有没有更简洁的解决方案?
我就是这样做的.一个很好的方面bindAll是,如果你添加额外的功能,LocationFormView他们将自动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
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
443 次 |
| 最近记录: |