Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I had learned that following piece of code is bad because it is obstrusive javascript and mixes presentation with logic:

<a href="" onclick="archive()">archive</a>

The best practice was to add some sort of identifier to the link element and then bound an event to it on a separate file. Something among those lines

$("#archive").click(function() {
    //do stuff
});

See: Why is using onclick() in html a bad practice

How come now most Javascripts MVC frameworks like Backbone.js, Angular.js, etc now encourage pieces of code like this:

<a href="" ng-click="archive()">archive</a> 

Taken from: http://angularjs.org/#todo-html

Why is this now ok?

share|improve this question
1  
Adding event on tag with an ID is just tiny bit better, then <tag onclick="" .. Also, since when you have begun looking at frameworks for good practices. As if Rails and CodeIgniter are not enough to deter you. –  teresko Apr 12 '13 at 20:45

2 Answers 2

To be honest, I consider it ugly because of the () which look too much like eval'd code.

However, the reason why it's still "clean" is that you are not dealing with a global function or are able/encouraged to put arbitrary code in that attribute. Instead you specify that the element will use the method with the given name in the controller.

share|improve this answer
1  
Your first argument is not compelling; I'm used to curly-brace languages, and the parentheses are a nice visual cue that it's making a method call. –  Robert Harvey Apr 12 '13 at 21:06
1  
Your second argument is more convincing. The only coupling that is in play is the method name, which you would need anyway to get Model-View-Controller. –  Robert Harvey Apr 12 '13 at 21:08

I'm no expert, but I would assume the answer has to do with the fact that you don't want your view model knowing anything about the view. Backbone and Angular are considered MVVM frameworks, often using a sort of "command" pattern where the view most notify the VM that an event has occurred.

Not all MVVM frameworks use the same syntax. Knockout "looks" like it provides a bit more separate, even though it does roughly the same thing as the other frameworks.. http://knockoutjs.com/examples/helloWorld.html

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.