【问题标题】:Knockout binding fontawesome class淘汰赛绑定 fontawesome 类
【发布时间】:2019-01-14 06:26:50
【问题描述】:

Exmaple of posted code

你好,

我在将 font-awesome 的 CSS 类绑定到标签时遇到问题。

HTML:

    <div class="flex-no-shrink">
        <div class="btn-group">
            <div data-bind="foreach: toolbarButtons">
                <button type="button" class="btn btn-xs btn-primary" data-bind="enable: enabled, visible: visible, click: onClick">
                   <i class="fa" data-bind="css: { class: icon }"></i>
                    <!-- <i class="fa fa-plus"></i> -->
                </button>
                  <button type="button" class="btn btn-xs btn-primary" data-bind="enable: enabled, visible: visible, click: onClick">
                     <i class="fa fa-plus"></i>
                </button>
            </div>
        </div>
    </div>

TS:

interface IToolbarButton {
    enabled: KnockoutComputed<boolean>;
    visible: KnockoutComputed<boolean>;
    icon: string;
    onClick();
}

export abstract class ViewModel {
       toolbarButtons: IToolbarButton[];

   constructor(){
   this.loadDefaultToolbar();
   }
   loadDefaultToolbar(): void {
        this.toolbarButtons = [];
        //add button
        this.toolbarButtons.push({
            enabled: knockout.pureComputed(() => true/*some internal logic*/),
            icon: 'fa fa-plus',//this is what I want to place inside <i> tag
            onClick: () => {/*some internal logic*/},
            visible: knockout.pureComputed(() => true/*some internal logic*/)
        });
        //other default buttons...
        }
};

ko.applyBindings(new ViewModel());

在我的情况下正确的绑定方法是什么?

Exmaple of posted code

我尝试了像 text 或只是 css: { icon } 之类的基本绑定,但它们现在也可以使用。

感谢您的宝贵时间和帮助????

【问题讨论】:

    标签: typescript data-binding knockout.js javascript-databinding knockout-3.4


    【解决方案1】:

    css 绑定有两种形式:

    1. 接受一个对象,其中类作为属性名称,值作为布尔表达式:

      css: {className: booleanExpression}
      

      ...如果booleanExpression 为真,则className 是要包含的类的名称(如果booleanExpression 为假,它将被忽略)。

    2. 一个允许您指定要包含为字符串的类名:

      css: stringExpression
      

    您已经尝试过将这两种语法结合起来;你想要第二个。与(错误)使用 attr 绑定不同,这尊重添加到元素的其他类。 css 绑定的这个特性是documented here,可以在source here 中找到。

    现场示例:

    ko.applyBindings({
      someClassName: "two",
    })
    .one { background: yellow; }
    .two { color: red; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
    <div class="one" data-bind="css: someClassName">
      My type is red because the view model added a class name!
    </div>

    如果您想查看/比较更多示例,请发表评论。

    【讨论】:

    • (希望您不介意添加内容,我希望在某个时候删除我的答案...)
    猜你喜欢
    • 2013-02-04
    • 2013-10-31
    • 2013-08-14
    • 1970-01-01
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多