Knockout data-bind click

你离开我真会死。 提交于 2019-12-25 09:02:26

问题


I am trying to understand a button on a third party site my company uses. The button signs up a user for a class.

<a class="btn btn-large btn-blue" href="javascript:void(0);" 
        data-bind="click: $root.clickAction.bind($data, ActionType)">
        <span data-bind="text: Title">Sign up</span></a>

I was hoping to provide this button on a page in our company internal website, but I am not familiar with Knockout. I understand a GET request so if that button did something like this then I would get it.

thirdparty.com?method=register&classId=1234&userId=abcde

Is it even feasible to turn that knockout button into a GET or to somehow provide the signup mechanism on our internal sites to this 3rd party site? I can certainly paste more of the source as I'm sure more is needed.

I've tried using Firefox developer tools and viewing network traffic. I don't want to keep spinning my wheels if this isn't doable.


回答1:


Knockout provides several objects to access different levels of context and $root is of them. The $root object represents the main view model object in the root context. For instance, if your HTML element is inside another binding context, such as inside a foreach, and you want to use a root view model's method in each iteration:

 var ViewModel = function() {
    this.actionTypes = ko.observableArray([
        { ActionType: "Type A", Title: "Title A"},
        { ActionType: "Type B", Title: "Title B"},
        { ActionType: "Type C", Title: "Title C"}]);

    this.clickAction = function(action) {
        // your ajax request would go here
        alert(action);
    }
};

ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="foreach: actionTypes">
    <a class="btn btn-large btn-blue" href="javascript:void(0);" data-bind="click: $root.clickAction.bind($data, ActionType)">
         <span data-bind="text: Title">Sign up</span>
    </a>
<div>


来源:https://stackoverflow.com/questions/42649511/knockout-data-bind-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!