【问题标题】:Knockout.js + Bootstrap TourKnockout.js + Bootstrap 之旅
【发布时间】:2014-11-11 14:54:53
【问题描述】:

我想将Knockout.jsBootstrap Tour 一起使用。特别是,我想将一些数据绑定点击处理程序附加到游览步骤中的按钮。

我创建了一个这样的简单游览:

var tour = new new Tour({
    steps: [
        {
            orphan: true,
            title: "Help Title",
            content: "<button data-bind='click: someBoundFunction'>Click me!</button>"
        }
    ]
});
tour.init();
tour.start(true);

是否可以使用这种绑定?或者由于 bootstraptour 的标记代码创建机制,这种绑定不会起作用?我这样尝试过,但是单击按钮不执行该功能,也不显示任何错误消息。

【问题讨论】:

    标签: javascript knockout.js bootstrap-tour


    【解决方案1】:

    Knockout 不会为新添加的元素自动更新绑定。不过有一个解决方法,请参阅此question(和related)。以下是基于此解决方法的可能解决方案。

    所以你有一个主视图模型,它开始你的游览:

    function ViewModel(){
        var self = this;
        this.tour = new Tour({ 
            steps: [
                {
                    orphan: true,
                    title: "Help Title",
                    content: '<button id="newButton" data-bind="click: showMessage">showMessage</button>',
                    onShown: function(tour) {
                        // apply the bindings after content is added
                        ko.applyBindings(self, document.getElementById("newButton"));
                    }
                }
            ]
        });
        this.startTour = function() {
            this.tour.init();        
            self.tour.start(true);        
        }
        this.showMessage = function() {
            alert('Hello!');
        }
    }
    

    Working demo.

    【讨论】:

    • 谢谢,这会奏效。 onShownFunction 呢?这可以保存超时黑客吗?
    • @MichaelHilus,很好,我怎么能错过。我已经更新了我的答案以使用 onShown 事件处理程序,没有任何肮脏的黑客,谢谢!
    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 1970-01-01
    • 2012-06-22
    • 1970-01-01
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多