javascript - How can I refer back to my object in the method I pass to getJSON as success callback? -
in model i'm loading json after dispatch event whoever listening stating json has loaded.
my problem scope. found way 'main' listen model (using jquery's trigger method) prefixing scope variable (inside function model (applicationmodel) ) jquery alias.
my hunch may missing less confusing way of dealing scope in situation.
main:
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 ); } });
applicationmodel:
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; });
modify module this:
define( [ "jquery" ], function( $ ) { function model() { // cache $(this) don't call jquery time. this.$this = $(this); }; model.prototype.getjson = function() { // use bind `this` has proper value in `loadsuccess`. $.getjson( "/gettextfields", this.loadsuccess.bind(this) ); }; model.prototype.loadsuccess = function( data ) { console.log('loadsuccess', data ); // used cached `$this` rather recomputing. this.$this.trigger( "jsonloaded", [ data ] ); } return model; });
the key here using bind
. creates new function value of this
set first argument passed bind
.
Comments
Post a Comment