每个MVC框架都爱搞个todos演示
它的HTML如下:
<!--[if IE 6]><center style="display:inline-block;zoom:1;text-align:left;"> <![endif]--> <div id="todoapp"> <header> <h1>Todos</h1> <input id="new-todo" type="text" placeholder="What needs to be done?" data-on-keypress="addPost"> </header> <section id="main" data-display="show"> <input id="toggle-all" type="checkbox" data-on-click="checkAll"> <label for="toggle-all">Mark all as complete</label> <ul id="todo-list" data-each-post="posts"> <li data-on-dblclick="edit" > <div class="view"> <input class="toggle" type="checkbox" data-on-click="togglePost" /> <label data-text="post.title"></label> <a class="destroy" data-on-click="removePost"></a> </div> <input class="edit" type="text" data-value="post.title" data-on-blur="blur" /> </li> </ul> </section> <footer data-display="show"> <a id="clear-completed" data-on-click="remove" data-display="donePosts">Clear completed</a> <div id="todo-count" data-html="leftPosts"> </div> </footer> </div> <!--[if IE 6]></center> <![endif]--> <div id="instructions"> Double-click to edit a todo. </div> <div id="credits"> Created by <br /> <a href="http://jgn.me/">Jérôme Gravel-Niquet</a>. <br />Rewritten by: <a href="http://addyosmani.github.com/todomvc">TodoMVC</a>. </div>
require("avalon,ready", function($) { var $$ = $.MVVM var VM = $$.toViewModel({ posts: [],//这是评论列表 addPost: function(e){//添加评论 if(this.value && e.keyCode == 13){ VM.posts.push({ title: this.value }) this.value = ""; } }, leftPosts: $$.compute( function(){//还剩下多少评论没打勾 var len = this.posts.length - $(".toggle:checked").length; return "<b>" + len +"</b>" + (len <= 1 ? "item" : "items") +" left" },["posts"]), donePosts: $$.compute( function(){//有多少评论被打勾 return $(".toggle:checked").length },["posts"]), removePost: function(){//移除单条评论 var index = $("#main .destroy").index(this) if(index != -1){ VM.posts.removeAt(index) } }, remove: function(){//移除所有被打勾的评论,通过erase方法,它传入一个元素,会找到它对应的VM中的数据 var array = VM.posts, array2 = [] $(".toggle:checked").each(function(el, i){ array.erase(el) }) }, edit: function() {//让那条评论可编辑 $(this).addClass("editing").siblings().removeClass("editing") $(this).find(".edit").focus(); }, show: $$.compute( function(){//如果存在评论就把列表显示出来 return this.posts.length; },["posts"]), blur: function(){//失去焦点就失去编辑状态 $(this).parents(".editing").removeClass("editing") }, checkAll: function(){//勾选或不勾选所有评论 var els = $(".toggle").attr("checked", this.checked) for(var i = 0,el; el = els[i++];){ VM.togglePost.call(el,this.checked); } }, togglePost: function(bool){ $$.notify("leftPosts",VM)//通知leftPosts更新 $$.notify("donePosts",VM) $(this).parents("li").toggleClass( "done",bool ); } }); $$.render(VM); })