我是backbonejs的新手。我正在嘗試將正確的this
對象傳遞給回調函數,其中該函數是該視圖的一種方法。有沒有更好的方法將「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
}
});
這是一個正確的方式來實現我想要什麼? 有沒有更少的詳細解決方案呢?
如果您打算使用CoffeeScript,而不是在函數定義中使用fat arrows =>來使用bind。做同樣的事情。 – Radek 2012-03-01 11:56:12