简体   繁体   English

在不使用箭头功能的情况下获取函数内部的主类对象

[英]getting main class object inside function without using arrow function

In my angular project, I am using datatable where I have row grouping and row callbacks. 在我的有角项目中,我正在使用数据表,其中有行分组和行回调。

datatable options 数据表选项

openPositionDatatableOptions = {
    sDom: 'rt<"bottom"p>',
    ajax: (data, callback, settings) => {
      this.service.getOpenPositions()
        .map(data => data.json().data).catch(this.handleError)
        .subscribe(jsondata => {
          this.openPositionsData = jsondata;
          jsondata.forEach(element => {
            if (element.side === 'SLD') {
              element.openQuantity = '-' + element.openQuantity;
            }
            element['delta'] = 0;
            element['pl'] = 0;
          });
          if (jsondata) {
            callback({
              aaData: jsondata
            });
          }
        },
        error => {
          this.notifiicationAlert('Some Error Occured While Retrieving Positions Data', 'WARNING');
        });
    },

    columns: [
      { data: 'account.brokerId' },
      { data: 'contract.localSymbol' },
      { data: 'openQuantity' },
      { data: 'delta' },
      { data: 'pl' },
      {
        data: null,
        orderable: false,
        defaultContent:
          '<a class="fa fa-remove" style="color:#8B0000"></a>',
        responsivePriority: 2
      }
    ],
    //Grouping By Row Logic
    "columnDefs": [
      { "visible": false, "targets": 0 }
    ],
    "order": [[0, 'asc']],
    "drawCallback": function (settings) {
      var api = this.api();
      var rows = api.rows({ page: 'current' }).nodes();
      var last = null;
      api.column(0, { page: 'current' }).data().each(function(group, i) {
        if (last !== group) {
          $(rows).eq(i).before(
            '<tr class="group"><td colspan="5"><div class="row"><div class="col-lg-6" style="text-align:left">' + group + '</div><div class="col-lg-6" style="text-align:right"><button class="datatableGroupingBtn btn btn-default btn-xs fa fa-remove" value='+group+'></button></div></div></td></tr>'
          );
          last = group;
        }
      });
      // jQuery button click event
      $(".datatableGroupingBtn").on('click',(value)=>{
        var clickedRow = value.currentTarget.value;
      });
    },
    //Grouping By Row Logic Ends
    rowCallback: (row: Node, data: any | Object, index: number) => {
      $('a', row).bind('click', () => {
        this.service.closePosition(data.id).catch(this.handleError).subscribe(
          res => {
            if (res.status == 200) {
              //TODO Re-implement this using web-socket
              if ($.fn.DataTable.isDataTable(this.service.openPositionTableAlias)) {
                const table = $(this.service.openPositionTableAlias).DataTable();
                if (this.openPositionsData.length > 1) {
                  $('td', row)
                    .parents('tr')
                    .remove();
                } else {
                  table.clear().draw();
                }
                this.notifiicationAlert('Position Closed Successfully', 'SUCCESS');
              }
            }
          },
          (error: Response) => {
            this.notifiicationAlert('Some Problem While Closing The Position', 'WARNING');
          }
        );
      });
      return row;
    }
  };

In my datatable options, I have a drawCallback function inside I am grouping the rows. 在我的数据表选项中,我在对行进行分组的内部具有drawCallback函数。 Inside the function, I also have a jquery click event over #datatableGroupingBtn 在函数内部,我在#datatableGroupingBtn还有一个jquery click事件

"drawCallback": function (settings) {
      var api = this.api();
      var rows = api.rows({ page: 'current' }).nodes();
      var last = null;
      api.column(0, { page: 'current' }).data().each(function(group, i) {
        if (last !== group) {
          $(rows).eq(i).before(
            '<tr class="group"><td colspan="5"><div class="row"><div class="col-lg-6" style="text-align:left">' + group + '</div><div class="col-lg-6" style="text-align:right"><button class="datatableGroupingBtn btn btn-default btn-xs fa fa-remove" value='+group+'></button></div></div></td></tr>'
          );
          last = group;
        }
      });
      // jQuery button click event
      $(".datatableGroupingBtn").on('click',(value)=>{
        var clickedRow = value.currentTarget.value;
      });
    }

Now my requirement is, I have to access the class level this that is My OrderComponent class object inside the jquery click event binding of #datatableGroupingBtn . 现在,我的要求是,我要访问类的水平this是jQuery的单击事件的结合在我的OrderComponent类对象#datatableGroupingBtn I know that this can be done if I use arrow function over the drawCallback but if I use then other required functionalities won't work as you can see that I have used some properties using function() level this inside drawCallback function. 我知道,如果我在drawCallback使用箭头功能,可以做到这drawCallback但是如果我使用了其他必需的功能,则将无法正常工作,因为您可以看到我已经在drawCallback函数中使用了一些使用function()级的属性。

My component 我的组件

import { NotificationService } from './../shared/utils/notification.service';
import { Global } from 'app/shared/global';
import { endponitConfig } from 'environments/endpoints';
import { Observable } from 'rxjs';
import { Http } from '@angular/http';
import { OrderService } from './order.service';
import { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';
import { Router } from '@angular/router';

declare var $: any;

@Component({
  selector: 'app-order',
  templateUrl: './order.component.html',
  styleUrls: ['./order.component.css']
})
export class OrderComponent {

  openPositionsData: any;
  openOrdersData: any;

  openPositionDatatableOptions = {
    sDom: 'rt<"bottom"p>',
    ajax: (data, callback, settings) => {
      this.service.getOpenPositions()
        .map(data => data.json().data).catch(this.handleError)
        .subscribe(jsondata => {
          this.openPositionsData = jsondata;
          jsondata.forEach(element => {
            if (element.side === 'SLD') {
              element.openQuantity = '-' + element.openQuantity;
            }
            element['delta'] = 0;
            element['pl'] = 0;
          });
          if (jsondata) {
            callback({
              aaData: jsondata
            });
          }
        },
        error => {
          this.notifiicationAlert('Some Error Occured While Retrieving Positions Data', 'WARNING');
        });
    },

    columns: [
      { data: 'account.brokerId' },
      { data: 'contract.localSymbol' },
      { data: 'openQuantity' },
      { data: 'delta' },
      { data: 'pl' },
      {
        data: null,
        orderable: false,
        defaultContent:
          '<a class="fa fa-remove" style="color:#8B0000"></a>',
        responsivePriority: 2
      }
    ],
    //Grouping By Row Logic
    "columnDefs": [
      { "visible": false, "targets": 0 }
    ],
    "order": [[0, 'asc']],
    "drawCallback": function (settings) {
      var api = this.api();
      var rows = api.rows({ page: 'current' }).nodes();
      var last = null;
      api.column(0, { page: 'current' }).data().each(function(group, i) {
        if (last !== group) {
          $(rows).eq(i).before(
            '<tr class="group"><td colspan="5"><div class="row"><div class="col-lg-6" style="text-align:left">' + group + '</div><div class="col-lg-6" style="text-align:right"><button class="datatableGroupingBtn btn btn-default btn-xs fa fa-remove" value='+group+'></button></div></div></td></tr>'
          );
          last = group;
        }
      });
      // jQuery button click event
      $(".datatableGroupingBtn").on('click',(value)=>{
        var clickedRow = value.currentTarget.value;
      });
    },
    //Grouping By Row Logic Ends
    rowCallback: (row: Node, data: any | Object, index: number) => {
      $('a', row).bind('click', () => {
        this.service.closePosition(data.id).catch(this.handleError).subscribe(
          res => {
            if (res.status == 200) {
              //TODO Re-implement this using web-socket
              if ($.fn.DataTable.isDataTable(this.service.openPositionTableAlias)) {
                const table = $(this.service.openPositionTableAlias).DataTable();
                if (this.openPositionsData.length > 1) {
                  $('td', row)
                    .parents('tr')
                    .remove();
                } else {
                  table.clear().draw();
                }
                this.notifiicationAlert('Position Closed Successfully', 'SUCCESS');
              }
            }
          },
          (error: Response) => {
            this.notifiicationAlert('Some Problem While Closing The Position', 'WARNING');
          }
        );
      });
      return row;
    }
  };

  constructor(private http : Http, private service : OrderService){
     this.http.get(Global.serviceUrl).subscribe(response=>{
        this.openPositionsData = response.json().data;
     })
  }

}

Inside the method your jQuery event binding is, declare a variable like so 在jQuery事件绑定的方法内部,声明一个像这样的变量

let self = this;

now you should be able to use this variable in your jquery click event binding 现在您应该能够在您的jquery click事件绑定中使用此变量

Assign your openPositionDatatableOptions in the constructor, after declaring a self variable 声明self变量后,在构造函数中分配openPositionDatatableOptions

openPositionDatatableOptions : any;

constructor()
{
    const self = this;

    this.openPositionDatatableOptions = {

    //....

    "drawCallback": function (settings) {
  //....
  // jQuery button click event
  $(".datatableGroupingBtn").on('click',(value)=>{
    var clickedRow = value.currentTarget.value;
    console.log(self);//<=== self is your class instance
  });
},


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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