【问题标题】:How to implement NativeScript Class in TypeScript with self delegate?如何使用自我委托在 TypeScript 中实现 NativeScript 类?
【发布时间】:2017-02-01 22:39:01
【问题描述】:

我正在创建一个包含 Swift CocoaPod 库的 NativeScript 插件。

在我的NativeScript plugin 中,我使用一个单独的类将所需的delegate 添加到主类。

是否可以在主类中实现委托方法,完全避免委托类?

即,

export class MicrosoftBandService  extends NSObject implements ConnectionDelegate {

  static new(): MicrosoftBandService {
    return <MicrosoftBandService>super.new()
  }

  constructor() {
    let _self= this;
    this.mbk = MicrosoftBand.alloc().init();
    this.mbk.connectDelegate = _self
  }

  onConnecte() {
    //

  onDisconnecte() {
    //
  }

  onErrorWithError(error) {
    //
  }

}

更好,我喜欢这样做

export class MicrosoftBandService  extends MicrosoftBand implements ConnectionDelegate {

  static new(): MicrosoftBandService {
    return <MicrosoftBandService>super.new()
  }

  constructor() {
    let _self= this;
    this.connectDelegate = _self
  }

  onConnecte() {
    //
  }

    onDisconnecte() {
      //
    }

    onErrorWithError(error) {
      //
    }

  }

我不知道在 TypeScript for NativeScript 中使用自委托实现构造函数的正确语法

我当前的代码有效,但我正在寻求帮助,以通过消除单独的委托类来简化和减少代码。

【问题讨论】:

  • 我只想添加一条评论;如果你可以避免使用 Swift;你最好这样做。 Swift 为应用程序增加了超过 20 兆的额外运行时。

标签: swift angular typescript nativescript angular2-nativescript


【解决方案1】:

当 TypeScript 转换为 Javascript 时,接口会丢失。所以你需要使用ObjCProtocols 静态字段并声明这个类实现了哪些协议:

export class MicrosoftBandService extends NSObject implements ConnectionDelegate {    
   public static ObjCProtocols = [ ConnectionDelegate ];
   ...
}

第二个 TypeScript 构造函数不会在本机对象上调用(您可能在控制台中对此有警告)。 所以你应该做init 方法并在那里设置所有字段:

public static initWithOwner(band: MicrosoftBand): MicrosoftBandService {
    let delegate = <MicrosoftBandService>MicrosoftBandService.new();
    delegate._band = band; 
    band._delegate = delegate;
    band.connectDelegate = delegate.
}

这里有几点需要注意:

  1. 避免 new() 过载。可能会导致某些本机对象出现问题。

  2. 传递带实例,以便您可以在委托方法中调用它(如果需要)

  3. 在乐队本地保留委托的引用 - 大多数委托被实现为弱引用。如果你不保留对它的引用,没有人会,它会在某个时候被 GC 收集。

关于协议实现的更多信息可以在这里找到: http://docs.nativescript.org/runtimes/ios/how-to/ObjC-Subclassing

编辑: 应该可以这样做:

export class MicrosoftBandService extends MicrosoftBand implements ConnectionDelegate

只要添加静态ObjCProtocols 字段即可。然后,您将不需要保留对委托的引用,因为它将是同一个实例。仍然不会调用 TypeScript 构造函数,因此您需要调用正确的 init 本机方法。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2019-10-07
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-05
相关资源
最近更新 更多