Javascript闭包:Phonegap和'这'在回调中

Javascript closure: Phonegap and 'this' in callback

本文关键字:回调 闭包 Javascript Phonegap      更新时间:2023-09-26

我需要在phonegap的通知插件的回调中传递对当前对象的引用。我很确定这涉及到闭包,但不能完全解决。

这是我的代码:

export default Ember.ArrayController.extend({ 
...
  delete: function(buttonIndex) {
    if (buttonIndex === 1) {
      // how to access 'this' here? 'self' doesn't work here either.
      console.log('Deleting survey with ID=' + this.get('obj_to_delete'));
    }
  },
  actions: {
    deleteAction: function(obj_id) {
    var self = this;
    this.set('obj_to_delete', obj_id);
    this.store.find('survey', obj_id).then(function(survey) {
       navigator.notification.confirm(
         'Are you sure you want to delete?', 
          self.delete,              // do i need some sort of closure binding self to this here?
          'Confirm delete',          
          ['Yes', 'No']         
        );
      }
    );
  }
}
});

如何在我的删除方法中获得对"this"的引用?

try:

navigator.notification.confirm( 'Are you sure you want to delete?', self.delete.bind(self), // do i need some sort of closure binding self to this here? 'Confirm delete',
['Yes', 'No']
);

在"self.delete.bind(self)"行中,我们将其绑定到函数"this.delete"。