[英]How can I refer back to my object in the method I pass to getJSON as success callback?
在我的模型中,我成功加載了一些JSON,然后我簡單地將一個事件發送給正在偵聽的人,說明JSON已加載。
我的問題是范圍。 我發現'main'能夠成功偵聽模型的唯一方法(使用jQuery的trigger方法)是在Scope變量(在函數Model(ApplicationModel)的內部)前面加上jQuery別名。
我的直覺是,在這種情況下,我可能會缺少一種不太混亂的處理范圍的方法。
主要 :
require( [ "jquery", "models/applicationModel", "views/applicationView" ], function( $, ApplicationModel, ApplicationView ) {
var appModel = new ApplicationModel();
$( appModel ).on( "jsonLoaded", onJsonLoaded );
appModel.getJson();
function onJsonLoaded( e, data ) {
console.log('main: onJsonLoaded', data );
}
});
應用模型 :
define( [ "jquery" ], function( $ ) {
function Model() {
$scope = this;
};
Model.prototype.getJson = function() {
$.getJSON( "/getTextfields", this.loadSuccess );
};
Model.prototype.loadSuccess = function( data ) {
console.log('loadSuccess', data );
$( $scope ).trigger( "jsonLoaded", [ data ] );
}
return Model;
});
修改模塊,使其執行以下操作:
define( [ "jquery" ], function( $ ) {
function Model() {
// Cache $(this) so that we don't call jQuery all the time.
this.$this = $(this);
};
Model.prototype.getJson = function() {
// Use bind so that `this` has the proper value in `loadSuccess`.
$.getJSON( "/getTextfields", this.loadSuccess.bind(this) );
};
Model.prototype.loadSuccess = function( data ) {
console.log('loadSuccess', data );
// Used the cached `$this` rather than recomputing.
this.$this.trigger( "jsonLoaded", [ data ] );
}
return Model;
});
這里的關鍵是使用bind
。 它為它的值的新功能, this
被設置為傳遞到第一個參數bind
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.