简体   繁体   English

将普通方法与淘汰模型视图模型绑定

[英]Binding a Normal Method With Knockout View model

I saw a piece of code regarding Knockout and went through it but I could not understand how this code works. 我看到了一段有关Knockout的代码,并进行了仔细研究,但我不明白该代码的工作原理。 Here is the complete code for binding a normal method with a Knockout viewmodel. 这是用于将常规方法与Knockout视图模型绑定的完整代码。

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/knockout-2.2.1.js"></script>
    <script src="Scripts/jquery-1.7.1.js"></script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <input type="button" data-bind="click: callalert" name="knockoutbtn" value="Call Knockout Method"/>
        <input type="button" name="normalbtn" id="nbtn" value="Call Normal Method"/>

        <script type="text/javascript">
            var callmethod = function () {   //Normal Method which would be 
                alert('hello');              //called from knockout binding   
            }                                //also from the normal button click  
            $(document).ready(function () {           //Binded the Method with normal button 
                $("#nbtn").live("click", callmethod);
            });

            ko.applyBindings({                        //Binded the method with ko view model
                callalert : callmethod
            });

        </script>
    </div>
    </form>
</body>
</html>  

I just do not understand what the meaning of this code is: data-bind="click: callalert" and also do not understand this code: 我只是不明白此代码的含义是: data-bind="click: callalert" ,也不了解此代码:

ko.applyBindings({                        //Binded the method with ko view model
                callalert : callmethod
            });

It seems that when the user clicks on the first button then a method will be called named callalert but in the code there is no method named callalert . 看来,当用户单击第一个按钮时,一个名为callalert的方法将被调用,但是在代码中没有名为callalert方法。 When the user clicks on the second button, then a method will be called named callmethod . 当用户单击第二个按钮时,一个方法将被称为callmethod

So please help me to understand the above code. 因此,请帮助我理解上面的代码。 Especially these two points 特别是这两点

1) data-bind="click: callalert"
2) ko.applyBindings({                        //Binded the method with ko view model
                    callalert : callmethod
                });

UPDATE 更新

suppose if anyone just see it below 假设有人在下面看到

var person = {
    firstName: 'John',
    lastName: 'Doe',
    sayHi: sayHiFunction,
    pets: ['Cat', 'Dog']
};

then how anyone would understand that sayHiFunction is a function because there is no bracket like sayHiFunction() ? 那么有人会怎么说sayHiFunction是一个函数,因为没有像sayHiFunction()这样的括号?

if you look the above code then u can see 如果你看上面的代码,那么你可以看到

$(document).ready(function () {           //Binded the Method with normal button 
      $("#nbtn").live("click", callmethod);
});

that callmethod is calling by jquery code. 该callmethod通过jquery代码进行调用。 so why twice it is define in code that callmethod need to be called when user click on button. 因此,为什么在代码中两次定义了在用户单击按钮时需要调用callmethod的原因。 once it is done by jquery and once it is done by knockout binding ? 一旦它由jquery完成,一旦它由敲除绑定完成? can u explain in detail. 你能详细解释一下吗?

if i remove the jquery portion then callmethod will be called when user click on button. 如果我删除了jQuery部分,那么当用户点击按钮时,就会调用callmethod。 waiting for your answer. 等待你的答复。 thanks 谢谢

Javascript objects Javascript对象

{ callalert : callmethod }

is a regular javascript object with one property: callalert . 是具有一个属性的常规javascript对象: callalert In JS, you can construct objects in a key-value-pair fashion: 在JS中,您可以按键值对的方式构造对象:

var person = {
    firstName: 'John',
    lastName: 'Doe',
    sayHi: function() {
        alert('Hi!');
    },
    pets: ['Cat', 'Dog']
};

This constructs an object that we put in a variable person and give four properties: two normal properties (of string type), one function and on array. 这个构建体,我们把在一个变量中的对象person ,并给四个属性:两个正常属性(串类型),一个功能和阵列。

Because in JS, functions are also objects, you can put them in variables and use them as such. 因为在JS中,函数也是对象,所以您可以将它们放在变量中并按原样使用它们。 So you can define a function and put it in a variable (as you are doing with your callmethod variable) and then assign it to a member of an object (as you are doing with the callalert property). 因此,您可以定义一个函数并将其放入变量中(就像您对callmethod变量所做的callmethod ),然后将其分配给对象的成员(就像您对callalert属性所做的callalert )。

This would also work in my example: 在我的示例中这也将起作用:

var sayHiFunction = function() {
    alert('Hi!');
};

var person = {
    firstName: 'John',
    lastName: 'Doe',
    sayHi: sayHiFunction,
    pets: ['Cat', 'Dog']
};

Knockout applyBindings 剔除applyBindings

Next, 下一个,

ko.applyBindings

accepts a javascript object. 接受一个javascript对象。 Usually, you would use an object with observable properties (properties handled by Knockout), but you can also have functions in it. 通常,您将使用具有可观察属性(由Knockout处理的属性)的对象,但是您也可以在其中包含函数。

In your case, you only have a function. 就您而言,您只有一个功能。 The implementation of the function is callmethod and the identifier to call is callalert . 该函数的实现是callmethod ,要调用的标识符是callalert

So if you would do: 因此,如果您愿意:

var myVariable = { callalert : callmethod };
myVariable.callalert();

you would get the alert. 您会收到警报。 You've effectively created an object with one member ( callalert ) which is a function (with the implementation of callmethod ), and put it in myVariable . 您已经有效地创建了一个具有一个成员的对象( callalert ),该成员是一个函数(具有callmethod的实现),并将其放入myVariable

Knockout data-bind 敲除数据绑定

Now, what data-bind="click: callalert" does is let Knockout know it should databind the click event to the callalert property of your viewmodel (the object you passed to applyBindings ). 现在, data-bind="click: callalert"作用是让Knockout知道它应该将click事件数据绑定到视图模型的callalert属性(传递给applyBindings的对象)。 So when you click on the button, Knockout will call the callalert method on the viewmodel. 因此,当您单击按钮时,Knockout将在视图模型上调用callalert方法。

Update - jQuery 更新-jQuery

The jQuery code is indeed more readable. jQuery代码确实更具可读性。 But when you have complex UIs, it will often require a lot of jQuery code (for hiding, showing, updating, etc controls). 但是,当您具有复杂的UI时,通常会需要很多jQuery代码(用于隐藏,显示,更新等控件)。 This can easily become hard to maintain and read. 这很容易变得难以维护和阅读。 For this, Knockout and its MVVM approach can help. 为此,Knockout及其MVVM方法可以提供帮助。

The reason the code has it twice, is for showing the difference I believe. 代码有两次的原因是为了显示我相信的差异。 The first button used Knockout to call the method, the second button uses jQuery. 第一个按钮使用Knockout调用方法,第二个按钮使用jQuery。

Both are valid approaches. 两者都是有效的方法。 In fact, I'd recommend jQuery if it's just that simple. 实际上,如果它很简单,我会推荐jQuery。 But if you have more complex UIs, or if your project uses it in other screens, you might want to go with Knockout. 但是,如果您具有更复杂的UI,或者您的项目在其他屏幕上使用它,则可能要使用Knockout。

As for 至于

how anyone would understand that sayHiFunction is a function because there is no bracket like sayHiFunction() ? 怎么会有人会说sayHiFunction是一个函数,因为没有像sayHiFunction()这样的括号?

You can't immediately, but you know it's a variable, so if you look for the variable, you'll find out. 您不能立即进行操作,但是您知道它是一个变量,因此,如果您查找该变量,就会知道。 But unless you need to set the implementation of the function dynamically at runtime, you'd have no reason to write it like this. 但是除非您需要在运行时动态设置函数的实现,否则您就没有理由这样写。 You'd write the function inline: 您可以内联编写函数:

var person = {
    sayHi: function() {
        alert('Hi');
    }
}

But even then, you can still change it: 但是即使如此,您仍然可以更改它:

person.sayHi = function() {
    alert('Hello!');
}

This makes JS a powerful language, but indeed not always easy to read for beginners. 这使JS成为一种功能强大的语言,但对于初学者来说确实并不总是那么容易阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM