繁体   English   中英

如何在传递给getJSON作为成功回调的方法中引用我的对象?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM