1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Binding</title> 5 <script src="lib/jquery.js" type="text/javascript" charset="utf-8"></script> 6 <script src="lib/jquery.tmpl.js" type="text/javascript" charset="utf-8"></script> 7 <script type="text/javascript" charset="utf-8"> 8 var addChange = function(ob){ 9 ob.change = function(callback){ 10 if(callback){ 11 if(!this._change){ 12 this._change = []; 13 } 14 this._change.push(callback); 15 }else{ 16 if(!this._change) return; 17 for(var i=0;i<this._change.length;i++){ 18 this._change[i].apply(this); 19 } 20 } 21 }; 22 }; 23 24 var object = {}; 25 object.name = "Foo"; 26 27 addChange(object); 28 object.change(function(){ 29 console.log("Change!",this); 30 //这里可以添加更新视图的代码 31 }); 32 object.change(); 33 34 object.name = "Bar"; 35 object.change(); 36 </script> 37 </head> 38 <body> 39 40 </body> 41 </html>
jquery.tmpl:
http://github.com/jquery/jquery-tmpl