gpt4 book ai didi

angularjs - AngularJS 中的模型 View ViewModel

转载 作者:行者123 更新时间:2023-12-03 10:14:53 25 4
gpt4 key购买 nike

我目前正在阅读 Manning's AngularJS in Action by Lukas Ruebbelke
在第一章中,他提出,

The controller is responsible for providing state for the view to bind to and commands that the view can issue back to the controller to do units of work. This frees up the view from having to maintain state (since it only has to display whatever state the controller is in) and it frees up the view from having to do any work (as the view always defers to the controller).



enter image description here

他所说的 是什么意思?为要绑定(bind)到 的 View 提供状态?

此外,他建议说,

Using a ViewModel inverts the application flow that traditionally existed in jQuerystyle applications. In jQuery, you would’ve queried the DOM and attached an event listener. When that event fired, you would try to interpret the event and parse the DOM for state so that you could perform some imperative operation. This forces a tight coupling between the HTML and the JavaScript that drives it. By introducing a ViewModel, you’re able to break this relationship. The controller no longer is responsible for listening to the view, but rather the view is responsible for issuing specific commands to the controller that it operates on.



最后一行让我感到困惑。

Controller 不再负责收听 查看 ,
而是 查看 负责 发出特定命令 Controller 它运行。

不是说儿子不再负责听父亲的话,而是父亲负责 发出特定命令 儿子 它(儿子)必须对其进行操作。

就算儿子不负责,其实也让儿子负责。但是他们(两者)上述陈述不是相似的吗?

他到底想表达什么?

最佳答案

这是我的理解。

Angular 来看,查看 是您的 HTML, Controller 是你的 Angular Controller (这并不奇怪)和查看型号 $scope您可以从 访问的对象要么 Controller 或 View (它有点像将 Controller 链接到 View 的胶水)。

为要绑定(bind)的 View 提供状态意味着 View 只知道如何显示数据(即它知道数据的结构),但无论如何,它不包含 实际数据 .此数据/状态由 的 Controller 持有。绑定(bind) 通过将数据“放置”到 $scope 上,将其放到 View 中。对象,从而让 View 访问数据并显示它。

The controller no longer is responsible for listening to the view, but rather the view is responsible for issuing specific commands to the controller that it operates on.



这是 告诉不要问设计模式。与其让 Controller 询问 View 是否有任何变化, View 会告诉 Controller 是否发生了这样的事情。

例如:假设我们有一个带有提交按钮的表单。如果有人点击了 jQuery 中的提交按钮,而不是让 Controller 询问 View :
$('submitButton').on('click', doSomething);

View 将发出 Controller 将执行的特定命令(方法)。因此, View 告诉 Controller 有人提交了表单:

Controller :
angular.module('myApp')
.controller('myController', ['$scope', function ($scope) {
$scope.submit = function () {
//process form here
}
}]);

看法:
<button ng-click="submit()">Submit Form</button>

如您所见,我们“附加”了 submit()方法到 $scope对象,以便我们可以调用 submit从 View 。

关于angularjs - AngularJS 中的模型 View ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32154741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com