事件处理程序将WinJS.UI.Repeater项绑定到Object方法

时间:2016-08-04 06:02:35

标签: javascript windows windows-store-apps uwp winjs

我目前正试图将onchange的{​​{1}}事件绑定到一个事件处理程序里面,这是一个对象方法(用TypeScript编写的JavaScript类),如下所示:

HTML:



<select>
&#13;
&#13;
&#13;

JS /打字稿:

&#13;
&#13;
<div id="readerTemplate" data-win-control="WinJS.Binding.Template">
  <div>
    <select class="win-dropdown" 
            data-win-control="WinJS.UI.Repeater" 
            data-win-options="{data: versions}" 
            data-win-bind="value: version; onchange: versionChangeHandler">
      <option data-win-bind="value: fileName; textContent: versionName">
      </option>
    </select>
    <div class="win-type-title" data-win-bind="textContent: version"></div>
  </div>
</div>
&#13;
&#13;
&#13;   

发生绑定的行:
loadTabsUI(pivot: WinJS.UI.Pivot) { for (let tab of this.tabs) { var tabDiv = document.createElement("div"); var pivotItemDiv = document.createElement("div"); var pivotItem = new WinJS.UI.PivotItem(pivotItemDiv); pivotItemDiv.setAttribute('data-win-bind', 'winControl.header: title'); var rptrDiv = document.createElement("div"); var rptr = new WinJS.UI.Repeater(rptrDiv, { "data": tab.readers, "template": document.getElementById("readerTemplate").winControl }); pivotItem.contentElement.appendChild(rptrDiv); pivot.items.push(pivotItem); WinJS.Binding.processAll(pivotItemDiv, tab); } }

Reader类与方法:

&#13;
&#13;
var rptr = new WinJS.UI.Repeater(rptrDiv, { "data": tab.readers, "template": document.getElementById("readerTemplate").winControl });
&#13;
&#13;
&#13;

class Reader { ... ... versionChangeHandler(evt: UIEvent): void { // goal is to execute the following line: this.setVersionAsync((evt.target as any).value); } ... ... }的选择发生变化时,<select>会被调用。但是,问题是我无法访问函数内部的正确versionChangeHandler,这阻止我在正确的对象实例上运行this,这是使用的对象实例通过setVersionAsync(在前面的JS绑定中)填充/绑定WinJS.UI.Repeater

有关解决此问题的任何想法? (我在Reader类的构造函数中调用此readerTemplate,否则我使用绑定命中了异常。)

谢谢!

1 个答案:

答案 0 :(得分:1)

  

然而,问题是我无法在函数内部访问正确的内容。

这是因为背景已经改变。您可以使用以下代码来解决此问题:

class Reader {
   public handlerProxy: any;

   constructor() {
     this.handlerProxy = (evt: UIEvent) => { this.versionChangeHandler(evt, this); }
   }
   ...
   ...
   versionChangeHandler(evt: UIEvent,that): void {
     // goal is to execute the following line:
     that.setVersionAsync((evt.target as any).value);
   }
  ...
  ...
}

并在您的HTML中将versionChangeHandler更改为handlerProxy

<div id="readerTemplate" data-win-control="WinJS.Binding.Template">
<div>
<select class="win-dropdown" 
        data-win-control="WinJS.UI.Repeater" 
        data-win-options="{data: versions}" 
        <!--here change versionChangeHandler to handlerProxy.-->
        data-win-bind="value: version; onchange: handlerProxy">
  <option data-win-bind="value: fileName; textContent: versionName">
  </option>
</select>
<div class="win-type-title" data-win-bind="textContent: version"></div>