具有动作属性的KnockoutObservableArray类型按钮不能正确分配动作

时间:2016-04-22 01:29:25

标签: loops dynamic knockout.js typescript click

我正在使用动态按钮创建动态弹出窗口,但在使用其动作时出现问题。

按钮的创建代码:

openPopup = (buttons: Array<popupButtonsModel>, title?: string, description?: string) => {
    var self = this;
    self.popup().isVisible(false);
    var action: any;
    for (var i: number = 0; i < buttons.length; i++) {
        action = buttons[i].action;
        var button = popupHelper.createPopupButton(buttons[i].text ? buttons[i].text : "Tamam",
            action ? function () { action; self.popup().isVisible(false); } : function () { self.popup().isVisible(false); });
        buttons[i] = button;
    }
    self.popup(popupHelper.createPopup(buttons, title, description));
}

当我点击按钮时,调试器显示我的动作值是(及其未定义)

buttons[i].action // should be {alert('Example');}

此代码正确显示我的按钮,但操作错误。如果我将操作未定义为按钮,则它可以正常工作为“function(){self.popup()。isVisible(false);});”因为条件。

我的观点:

 <!-- ko if:popup().isVisible-->
<div class="loader-container popup-dialog">
    <div class="panel panel-success modal-dialog">
        <div class="panel-heading">{{popup().title}}</div>
        <div class="panel-body">{{popup().description}}</div>
        <div data-bind="foreach:popup().buttons" class="panel-footer">
            <button data-bind="click:$data.action">{{$data.text}}</button>
        </div>
    </div>
</div>
<!--/ko-->

viewmodel上的Popup变量是:

import popupModel = require('models/popup');
public popup: KnockoutObservable<popupModel> = ko.observable<popupModel>(new popupModel());

PopupModel:

import popupButtons = require('models/popup-buttons');
class PopupModel {
buttons: KnockoutObservableArray<popupButtons> = ko.observableArray<popupButtons>([]);
isVisible: KnockoutObservable<boolean> = ko.observable(false);
title: KnockoutObservable<string> = ko.observable("");
description: KnockoutObservable<string> = ko.observable("");
}
export = PopupModel;

PopupButtonModel:

class PopupButtons {
action: any;
text: string;
}
export = PopupButtons;

弹出-助手:

import popupButtons = require('models/popup-buttons');

import popupModel = require('models / popup'); class PopupManager {     public static createPopup(buttons:Array,title?:string,description?:string){         var popup:popupModel = new popupModel();         popup.buttons(按钮);         popup.title(title?title:“Hata”);         popup.description(描述?描述:“İşleminizişuandgerçekleştiremiyoruz,lütfentekrardeneyiniz。”);         popup.isVisible(真);         返回弹出窗口;     }

public static createPopupButton(text?: string, action?: any) {
    var button: popupButtons = new popupButtons();
    button.text = text;
    button.action = action;
    return button;
}

public static hidePopup(popup: popupModel) {
    popup.isVisible(false);
}
}

export = PopupManager;

0 个答案:

没有答案