Angular在HTML属性中使用内联JavaScript并不是“不好的做法"吗? [英] Angular's use of Inline JavaScript in HTML attributes is not "bad practice"?

查看:43
本文介绍了Angular在HTML属性中使用内联JavaScript并不是“不好的做法"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我阅读Angular教程时,我真的很喜欢它,但是"ng-click"不等同于内联onClick吗?我的理解是JavaScript社区已经确定HTML中的内联JavaScript事件处理程序是错误的做法".

As I read through the Angular tutorials, I really like a lot of it, but isn't "ng-click" the equivalent of an inline onClick? My understanding was that the JavaScript community had determined inline JavaScript event handlers in your HTML was "bad practice."

<img ng-src="{{img}}" ng-click="setImage(img)">

很高兴知道为什么在使用Angular时不再认为这是不正确的".

It would be great to know why this is no longer considered "incorrect" when using Angular.

来源: http://docs.angularjs.org/tutorial/step_10

推荐答案

确实,这全都归结为以下事实:必须以某种方式将视图代码连接到应用程序逻辑中. AngularJS的最佳实践通常要求您编写自己的模型(代表您的业务领域的对象)并将其附加到范围.想象一下这样的代码:

Really, it all comes down to the fact that your view code has to be hooked into your application logic somehow. Best practices for AngularJS generally state that you should write your own models--objects that represent your business domain--and attach them to the scope. Imagine some code like this:

<img ng-src="{{img}}" ng-click="myProfile.setMainImage(img)">

myApp.controller("ProfileController", function($scope, myProfile) {
  $scope.myProfile = myProfile;
});

视图显示单击此图像时,它将在myProfile上调用setMainImage()."业务逻辑位于myProfile内部,可以在其中进行测试,等等.该视图只是一个钩子.

The view says "when this image is clicked, it will call setMainImage() on myProfile." The business logic is inside myProfile, where it can be tested, etc. The view is just a hook.

在更传统"的情况下,或香草" jQuery设置,您必须编写如下内容:

In a more "traditional" or "vanilla" jQuery setup, you'd have to write something like the following:

$("#someId img").on('click', function() {
  var img = $(this).attr('src');
  myProfile.setMainImage(img); // where does myProfile come from here?
                               // how does it update the view?
});

当然,JavaScript社区已确定以这种方式编写大型应用程序实际上并不可行,部分原因是视图与模型对象之间的脱节(如代码片段中的注释所示),这这就是为什么我们首先拥有Angular之类的框架的原因.

Of course, the JavaScript community has determined that writing large applications in this fashion isn't really tenable, in part because of the disconnect between the views and the model objects (as indicated by the comments in the code snippet), which is why we have frameworks like Angular in the first place.

因此,我们知道此本地jQuery代码并不理想,但我们仍不确定整个ngClick内容.让我们将其与提供MV *架构的另一个非常流行的JavaScript框架Backbone进行比较.在AngularJS上最近的RailsCasts一集中,有人问了一个非常相似的问题:

So, we know this native jQuery code is not ideal, but we're still not sure about the whole ngClick thing. Let's compare it to another very popular JavaScript framework that provides an MV* architecture, Backbone. In a recent RailsCasts episode on AngularJS, someone asked a very similar question:

是我一个人,还是AngularJS看起来是个坏主意?瑞安(Ryan),请不要误解我的意思,这一集很棒,但是我对框架不满意.

Is it just me, or AngularJS looks so a bad idea? Ryan, don't get me wrong, the episode was great, but I'm not convinced by the framework.

所有ng-showng-repeatng-class看起来都像旧的Java的JSF以及类似的框架.它还使用ng-submitng-click强制使用了令人讨厌的JS.

All that ng-show, ng-repeat, ng-class are looking like the old Java's JSF, and similar frameworks. It also enforces obtrusive JS with ng-submit and ng-click.

因此,我的观点是:您的视图将很容易变得混乱并且完全依赖于它. Backbone等其他框架的优点是,可以将表示和行为(较少或没有依赖性)和结构化的客户端应用程序(MVVM)之间的关注点分离.

So my point is: your view will easily become cluttered and totally dependent on it. The advantage of other frameworks like Backbone, is to have a separation of concerns between the presentation and the behavior (less or no dependencies), and a structured client side application (MVVM).

我的回复也适用于此:

在类似Backbone的框架中,您将具有以下代码(从Backbone网站获取,减去几行):

In a framework like Backbone, you'd have something like the following code (taken from the Backbone website, minus a few lines):

var DocumentView = Backbone.View.extend({

  events: {
    "dblclick"                : "open",
    "click .icon.doc"         : "select",
    "contextmenu .icon.doc"   : "showMenu",
    "click .show_notes"       : "toggleNotes",
    "click .title .lock"      : "editAccessLevel",
    "mouseover .title .date"  : "showTooltip"
  },

  open: function() {
    window.open(this.model.get("viewer_url"));
  },

  select: function() {
    this.model.set({selected: true});
  },

});

在该对象这是一个视图中,您正在各种元素上设置事件处理程序.这些事件处理程序在视图对象上调用函数,这些函数委托给模型.您还可以在各种模型事件(例如change)上设置回调,这些回调又会​​在视图对象上调用函数以相应地更新视图.

In this object which is a view, you are setting up event handlers on various elements. These event handlers call functions on the view object, which delegate to models. You also set up callbacks on various model events (such as change) which in turn call functions on the view object to update the view accordingly.

在Angular中,DOM是您的视图.使用ng-clickng-submit等时,您正在这些元素上设置事件处理程序,这些处理程序调用应委托给模型对象的函数.使用ng-showng-repeat等时,您将在更改视图的模型事件上设置回调.

In Angular, the DOM is your view. When using ng-click, ng-submit, etc., you are setting up event handlers on these elements, which call functions that should delegate to model objects. When using ng-show, ng-repeat, etc. you are setting up callbacks on model events that change the view.

AngularJS在后台为您设置这些[hooks和]回调的事实是无关紧要的;与Backbone之类的唯一区别是Angular允许您声明性地编写视图-描述视图 的内容-而不是命令性地描述视图的功能.

The fact that AngularJS sets up these [hooks and] callbacks behind the scenes for you is irrelevant; the only difference between this and something like Backbone is that Angular lets you write your view declaratively--you describe what your view is--rather than imperatively--describing what your view does.

因此,最后,<a ng-click="model.set({selected: true})">实际上添加的依赖项不超过

So, in the end, <a ng-click="model.set({selected: true})"> really adds no more dependencies than

events: {
  'click a': 'select'
},

select: function() {
  this.model.set({selected: true});
}

...但是可以肯定,这真是少了很多代码. ;)

...but it sure is a hell of a lot less code. ;)

(注意:实际上,Angular版本应该为<a ng-click="select()">,作用域上的select方法类似于Backbone示例视图中的select方法.)

(Note: really, the Angular version should be <a ng-click="select()">, and the select method on the scope would be like the select method in the view in the Backbone example.)

现在,也许合法担心的是您不喜欢标记中的事件挂钩.就我个人而言,我非常喜欢Angular视图的声明性质,其中您的标记描述了什么是视图,并且您在事件(无论是用户生成还是简单地在模型中进行更改)与事件之间有两种绑定方式视图-我发现我编写的模板代码要少得多,以连接事件(尤其是由模型的更改驱动的视图更改),而且我认为通常更容易推断视图.

Now, perhaps a legitimate concern is that you don't like the event hooks in your markup. Personally, I greatly prefer the declarative nature of Angular's views, where your markup describes what the view is and you have two way binding between events (whether they be user generated or simply changes in the model) and your views--I find I write far less boilerplate code to hook up events (especially changes in the view driven by changes in the models), and I think it's easier to reason about the view in general.

这篇关于Angular在HTML属性中使用内联JavaScript并不是“不好的做法"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆