作为一个jQuery的老用户,如何适应AngularJS的编程思想?

1. Don‘t design your page, and then change it with DOM manipulations

In jQuery, you design a page, and then you make it dynamic. This is because jQuery was designed for augmentation and has grown incredibly from that simple premise.

But in AngularJS, you must start from the ground up with your architecture in mind. Instead of starting by thinking "I have this piece of the DOM and I want to make it do X", you have to start with what you want to accomplish, then go about designing your application, and then finally go about designing your view.

2. Don‘t augment jQuery with AngularJS

Similarly, don‘t start with the idea that jQuery does X, Y, and Z, so I‘ll just add AngularJS on top of that for models and controllers. This is really tempting when you‘re just starting out, which is why I always recommend that new AngularJS developers don‘t use jQuery at all, at least until they get used to doing things the "Angular Way".

I‘ve seen many developers here and on the mailing list create these elaborate solutions with jQuery plugins of 150 or 200 lines of code that they then glue into AngularJS with a collection of callbacks and $applys that are confusing and convoluted; but they eventually get it working! The problem is that in most cases that jQuery plugin could be rewritten in AngularJS in a fraction of the code, where suddenly everything becomes comprehensible and straightforward.

The bottom line is this: when solutioning, first "think in AngularJS"; if you can‘t think of a solution, ask the community; if after all of that there is no easy solution, then feel free to reach for the jQuery. But don‘t let jQuery become a crutch or you‘ll never master AngularJS.

3. Always think in terms of architecture

First know that single-page applications are applications. They‘re not webpages. So we need to think like a server-side developer in addition to thinking like a client-side developer. We have to think about how to divide our application into individual, extensible, testable components.

So then how do you do that? How do you "think in AngularJS"? Here are some general principles, contrasted with jQuery.

The view is the "official record"

In jQuery, we programmatically change the view. We could have a dropdown menu defined as a ul like so:

<ul class="main-menu">    <li class="active">        <a href="#/home">Home</a>    </li>    <li>        <a href="#/menu1">Menu 1</a>        <ul>            <li><a href="#/sm1">Submenu 1</a></li>            <li><a href="#/sm2">Submenu 2</a></li>            <li><a href="#/sm3">Submenu 3</a></li>        </ul>    </li>    <li>        <a href="#/home">Menu 2</a>    </li></ul>

In jQuery, in our application logic, we would activate it with something like:

$(‘.main-menu‘).dropdownMenu();

When we just look at the view, it‘s not immediately obvious that there is any functionality here. For small applications, that‘s fine. But for non-trivial applications, things quickly get confusing and hard to maintain.

In AngularJS, though, the view is the official record of view-based functionality. Our ul declaration would look like this instead:

<ul class="main-menu" dropdown-menu>
    ...</ul>

These two do the same thing, but in the AngularJS version anyone looking at the template knows what‘s supposed to happen. Whenever a new member of the development team comes on board, she can look at this and then know that there is a directive called dropdownMenu operating on it; she doesn‘t need to intuit the right answer or sift through any code. The view told us what was supposed to happen. Much cleaner.

Developers new to AngularJS often ask a question like: how do I find all links of a specific kind and add a directive onto them. The developer is always flabbergasted when we reply: you don‘t. But the reason you don‘t do that is that this is like half-jQuery, half-AngularJS, and no good. The problem here is that the developer is trying to "do jQuery" in the context of AngularJS. That‘s never going to work well. The view is the official record. Outside of a directive (more on this below), you never, ever, never change the DOM. And directives are applied in the view, so intent is clear.

Remember: don‘t design, and then mark up. You must architect, and then design.

Data binding

This is by far one of the most awesome features of AngularJS and cuts out a lot of the need to do the kinds of DOM manipulations I mentioned in the previous section. AngularJS will automatically update your view so you don‘t have to! In jQuery, we respond to events and then update content. Something like:

$.ajax({
  url: ‘/myEndpoint.json‘,
  success: function ( data, status ) {
    $(‘ul#log‘).append(‘<li>Data Received!</li>‘);  }});

For a view that looks like this:

<ul class="messages" id="log"></ul>

Apart from mixing concerns, we also have the same problems of signifying intent that I mentioned before. But more importantly, we had to manually reference and update a DOM node. And if we want to delete a log entry, we have to code against the DOM for that too. How do we test the logic apart from the DOM? And what if we want to change the presentation?

This a little messy and a trifle frail. But in AngularJS, we can do this:

$http( ‘/myEndpoint.json‘ ).then( function ( response ) {
    $scope.log.push( { msg: ‘Data Received!‘ } );});

And our view can look like this:

<ul class="messages">    <li ng-repeat="entry in log">{{ entry.msg }}</li></ul>

But for that matter, our view could look like this:

<div class="messages">    <div class="alert" ng-repeat="entry in log">
        {{ entry.msg }}    </div></div>

And now instead of using an unordered list, we‘re using Bootstrap alert boxes. And we never had to change the controller code! But more importantly, no matter where or how the log gets updated, the view will change too. Automatically. Neat!

Though I didn‘t show it here, the data binding is two-way. So those log messages could also be editable in the view just by doing this: <input ng-model="entry.msg" />. And there was much rejoicing.

Distinct model layer

In jQuery, the DOM is kind of like the model. But in AngularJS, we have a separate model layer that we can manage in any way we want, completely independently from the view. This helps for the above data binding, maintains separation of concerns, and introduces far greater testability. Other answers mentioned this point, so I‘ll just leave it at that.

Separation of concerns

And all of the above tie into this over-arching theme: keep your concerns separate. Your view acts as the official record of what is supposed to happen (for the most part); your model represents your data; you have a service layer to perform reusable tasks; you do DOM manipulation and augment your view with directives; and you glue it all together with controllers. This was also mentioned in other answers, and the only thing I would add pertains to testability, which I discuss in another section below.

Dependency injection

To help us out with separation of concerns is dependency injection (DI). If you come from a server-side language (from Java to PHP) you‘re probably familiar with this concept already, but if you‘re a client-side guy coming from jQuery, this concept can seem anything from silly to superfluous to hipster. But it‘s not. :-)

From a broad perspective, DI means that you can declare components very freely and then from any other component, just ask for an instance of it and it will be granted. You don‘t have to know about loading order, or file locations, or anything like that. The power may not immediately be visible, but I‘ll provide just one (common) example: testing.

Let‘s say in our application, we require a service that implements server-side storage through a REST API and, depending on application state, local storage as well. When running tests on our controllers, we don‘t want to have to communicate with the server - we‘re testing the controller, after all. We can just add a mock service of the same name as our original component, and the injector will ensure that our controller gets the fake one automatically - our controller doesn‘t and needn‘t know the difference.

Speaking of testing...

4. Test-driven development - always

This is really part of section 3 on architecture, but it‘s so important that I‘m putting it as its own top-level section.

Out of all of the many jQuery plugins you‘ve seen, used, or written, how many of them had an accompanying test suite? Not very many because jQuery isn‘t very amenable to that. But AngularJS is.

In jQuery, the only way to test is often to create the component independently with a sample/demo page against which our tests can perform DOM manipulation. So then we have to develop a component separately and then integrate it into our application. How inconvenient! So much of the time, when developing with jQuery, we opt for iterative instead of test-driven development. And who could blame us?

But because we have separation of concerns, we can do test-driven development iteratively in AngularJS! For example, let‘s say we want a super-simple directive to indicate in our menu what our current route is. We can declare what we want in the view of our application:

<a href="/hello" when-active>Hello</a>

Okay, now we can write a test for the non-existent when-active directive:

it(‘should add "active" when the route changes‘, inject(function() {
    var elm = $compile(‘<a href="/hello" when-active>Hello</a>‘)($scope);
    $location.path("/not-matching");
    expect(elm.hasClass("active")).toBeFalsey();
    $location.path("/hello");
    expect(elm.hasClass("active")).toBeTruthy();
}));

And when we run our test, we can confirm that it fails. Only now should we create our directive:

.directive("whenActive", function($location) {
    return {
        scope:true,
        link:function(scope, element, attrs) {
            scope.$on("$routeChangeSuccess", function() {
                if ($location.path() == element.attr("href")) {
                    element.addClass("active");
                } else {
                    element.removeClass("active");
                }
            });
        }
    };
});

Our test now passes and our menu performs as requested. Our development is both iterative and test-driven. Wicked-cool.

5. Conceptually, directives are not packaged jQuery

You‘ll often hear "only do DOM manipulation in a directive". This is a necessity. Treat it with due deference!

But let‘s dive a little deeper...

Some directives just decorate what‘s already in the view (think ngClass) and therefore sometimes do DOM manipulation straight away and then are basically done. But if a directive is like a "widget" and has a template, it should also respect separation of concerns. That is, the template too should remain largely independent from its implementation in the link and controller functions.

AngularJS comes with an entire set of tools to make this very easy; with ngClass we can dynamically update the class; ngBind allows two-way data binding; ngShow and ngHide programmatically show or hide an element; and many more - including the ones we write ourselves. In other words, we can do all kinds of awesomeness without DOM manipulation. The less DOM manipulation, the easier directives are to test, the easier they are to style, the easier they are to change in the future, and the more re-usable and distributable they are.

I see lots of developers new to AngularJS using directives as the place to throw a bunch of jQuery. In other words, they think "since I can‘t do DOM manipulation in the controller, I‘ll take that code put it in a directive". While that certainly is much better, it‘s often still wrong.

Think of the logger we programmed in section 3. Even if we put that in a directive, we still want to do it the "Angular Way". It still doesn‘t take any DOM manipulation! There are lots of times when DOM manipulation is necessary, but it‘s a lot rarer than you think! Before doing DOM manipulation anywhere in your application, ask yourself if you really need to. There might be a better way.

Here‘s a quick example that shows the pattern I see most frequently. We want a toggleable button. (Note: this example is a little contrived and a skosh verbose to represent more complicated cases that are solved in exactly the same way.)

.directive("myDirective", function() {
    return {
        template:‘<a class="btn">Toggle me!</a>‘,
        link:function(scope, element, attrs) {
            var on = false;
            $(element).click(function() {
                if (on) {
                    $(element).removeClass("active");
                } else {
                    $(element).addClass("active");
                }
                on = !on;
            });
        }
    };
});

There are a few things wrong with this:

  1. First, jQuery was never necessary. There‘s nothing we did here that needed jQuery at all!
  2. Second, even if we already have jQuery on our page, there‘s no reason to use it here; we can simply use angular.element and our component will still work when dropped into a project that doesn‘t have jQuery.
  3. Third, even assuming jQuery was required for this directive to work, jqLite (angular.element) will always use jQuery if it was loaded! So we needn‘t use the $ - we can just use angular.element.
  4. Fourth, closely related to the third, is that jqLite elements needn‘t be wrapped in $ - the element that is passed to the link function would already be a jQuery element!
  5. And fifth, which we‘ve mentioned in previous sections, why are we mixing template stuff into our logic?

This directive can be rewritten (even for very complicated cases!) much more simply like so:

.directive( ‘myDirective‘, function () {
    return {
        scope: true,
        template: ‘<a class="btn" ng-class="{active: on}" ng-click="toggle()">Toggle me!</a>‘,
        link: function ( scope, element, attrs ) {
            scope.on = false;

            scope.toggle = function () {
                scope.on = !scope.on;
            };
        }
    };
});

Again, the template stuff is in the template, so you (or your users) can easily swap it out for one that meets any style necessary, and the logic never had to be touched. Reusability - boom!

And there are still all those other benefits, like testing - it‘s easy! No matter what‘s in the template, the directive‘s internal API is never touched, so refactoring is easy. You can change the template as much as you want without touching the directive. And no matter what you change, your tests still pass.

w00t!

So if directives aren‘t just collections of jQuery-like functions, what are they? Directives are actually extensions of HTML. If HTML doesn‘t do something you need it to do, you write a directive to do it for you, and then use it just as if it was part of HTML.

Put another way, if AngularJS doesn‘t do something out of the box, think how the team would accomplish it to fit right in with ngClick, ngClass, et al.

Summary

Don‘t even use jQuery. Don‘t even include it. It will hold you back. And when you come to a problem that you think you know how to solve in jQuery already, before you reach for the $, try to think about how to do it within the confines the AngularJS. If you don‘t know, ask! 19 times out of 20, the best way to do it doesn‘t need jQuery and to try to solve it with jQuery results in more work for you.

作为一个jQuery的老用户,如何适应AngularJS的编程思想?

时间: 2024-10-09 16:39:53

作为一个jQuery的老用户,如何适应AngularJS的编程思想?的相关文章

一个jQuery扩展工具包

带有详尽注释的源代码: var jQuery = jQuery || {}; // TODO // ###################################string操作相关函数################################### jQuery.string = jQuery.string || {}; /** * 对目标字符串进行html解码 * * @name jQuery.string.decodeHTML * @function * @grammar j

分享一个jquery插件,弥补一下hover事件的小小不足

hover事件有一个缺点:当你的鼠标无意划过一个dom元素(瞬间划过,这个时候用户可能不想触发hover事件),会触发hover事件 应该设置一个时差来控制hover事件的触发 比如jd左边的菜单 你用鼠标瞬间划过他子菜单会弹出然后立即消失, 用户体验非常的不好. 易迅的菜单就没有这个问题 delayHover来解决这个问题 啥也不说了先看调用---------- 调用方式: var duration = 500;// 延迟500毫秒 $('#div1').delayHover(function

面对一个&ldquo;丢失了与用户&ldquo;签订&rdquo;的协议的修改&rdquo;时进行的思考。

对于上图中的gauge,将value与label之间的比例值调整了,调整为1:1.2.这意味着,在新系统中打开老报表,老报表中的这个gauge的value可能会比以前大,二者可能是用户厌恶的效果. 严格来说,这个改动破坏了产品与用户"签订"的协议.用户升级后,以前做得报表的展现出现了变化. 但是我们最终还是这个改了,原因如下: 1.  这个变化很微小,用户应该不会注意到. 2.  如果在这里做兼容性,会导致产品的"较大"的冗余.结合第一点会显得得不偿失. 说实话,在

能用一个公式来计算用户体验吗?

能用一个公式来计算用户体验吗? 我对用一个公式来计算用户体验的追寻来源于一个实验,即我是否能计算一个设计的认知载入时间.当在谈论一个应用的载入速度时,我们常常把关注点放在界面的载入时间上,但是我们会忘了一点,那就是理解一个界面同样也是需要时间的,即所谓的“认知载入时间”.但当我越越来多地研究这个问题时,我越来越意识到载入时间――无论是界面上的还是认知上的――都可能只是一个更重要问题的一小部分,那就是:有没有可能把用户体验量化? 用户体验的问题在于――就像心理学――它是非常模糊的.很多人,包括我在

你真的需要一个jQuery插件吗

jQuery的插件提供了一个很好的方法,节省了时间和简化了开发,避免程序员从头开始编写每个组件.但是,插件也将一个不稳定因素引入代码中.一个好的插件节省了无数的开发时间,一个质量不好的插件会导致修复错误的时间比实际从头 开始编写组件的时间还长. 幸运的是,人们通常具有各种不同的插件可供选择.但是,即使你只用一个,也要弄清楚它是否值得使用的.永远不要在你的代码库中引入错误的代码. 你需要一个插件吗? 首先是要弄清楚究竟你是否需要一个插件.如果不需要,既可以节省文件大小,又可以节省自己的时间. 1.

使用HTML5、CSS3和jQuery增强网站用户体验[留存]

记得几年前如果你需要添加一些互动元素到你的网站中用来改善用户体验?是不是立刻就想到了flash实现?这彷佛年代久远的事了.使用现在最流行的Web技术HTML5,CSS3和jQuery,同样也可以实现类似的用户体验.而且使用这些特性将会比使用flash更加有效.也许你可能刚知道Adobe停止开发移动版flash的消息,虽然在桌面中我们还拥有大量的flash的应用,但是随着HTML标准的完善,可能flash也要退出历史舞台了.在今天这篇文章中,我们将介绍一些非常实用的教程,技巧和资源来帮助大家构建一

如何写一个Jquery 的Plugin插件

博客分类: Javascript /Jquery / Bootstrap / Web jQuery配置管理脚本FirebugJavaScript JQuery Plugin插件,如果大家不明白什么是JQuery插件或都不清楚如何编写可以查看其官方的网站:jQuery Authoring Guidelines 好了,下面有一些我觉得想做一个好的插件必须应有的要求: 1.在JQuery命名空间下声明只声明一个单独的名称 2.接受options参数,以便控制插件的行为 3.暴露插件的默认设置 ,以便外

一个移动开发老码农的书单

了解更多老码农的个人信息,爱八卦的,请看这里:http://www.koulianbing.com/?page_id=12 老码农是个比较宅的人,不爱玩游戏,只爱看书.过去10年来读的书中,还能记得的书大部都是很不错的,列出来推荐给大家.会持续更新. 一.开发技术 1.Effective Objective C 2.0 适合代码量在5000行以后阅读,对细节优化,性能提升,结构设计都非常有帮助,强烈建议所有iOS码农人手一本,至少读三遍. 2.Objective-C高级编程 日本人写的,薄薄的一

PHP处理大数据量老用户头像更新的操作

/** * @title 老用户头像更新--每3秒调用一次接口,每次更新10条数据 * @example user/createHeadPicForOldUser? * @method GET * @author 邹柯 */ public function createHeadPicForOldUserAction(){ $domain=$_SERVER['HTTP_HOST']; $ob = new UserModel(); $user=M('user'); $u_where="head_pi