jQuery.click() vs onClick

前端 未结 17 1520
情话喂你
情话喂你 2020-11-21 07:35

I have a huge jQuery application, and I\'m using the below two methods for click events.

First method

HTML

17条回答
  •  無奈伤痛
    2020-11-21 07:58

    Seperation of concerns is key here, and so the event binding is the generally accepted method. This is basically what a lot of the existing answers have said.

    However don't throw away the idea of declarative markup too quickly. It has it's place, and with frameworks like Angularjs, is the centerpiece.

    There needs to be an understanding that the whole

    Some Content
    was shamed so heavily because it was abused by some developers. So it reached the point of sacrilegious proportions, much like tables. Some developers actually avoid tables for tabular data. It's the perfect example of people acting without understanding.

    Although I like the idea of keeping my behaviour seperate from my views. I see no issue with the markup declaring what it does (not how it does it, that's behaviour). It might be in the form of an actual onClick attribute, or a custom attribute, much like bootstraps javascript components.

    This way, by glancing just at the markup, you can see what is does, instead of trying to reverse lookup javascript event binders.

    So, as a third alternative to the above, using data attributes to declarativly announce the behaviour within the markup. Behaviour is kept out of the view, but at a glance you can see what is happening.

    Bootstrap example:

    
    

    Source: http://getbootstrap.com/javascript/#popovers

    Note The main disadvantage with the second example is the pollution of global namespace. This can be circumvented by either using the third alternative above, or frameworks like Angular and their ng-click attributes with automatically scope.

提交回复
热议问题