knockoutjs(02) ko & jsrender
<ul data-bind="template: 'peopleList'"></ul> <script type="text/html" id="peopleList"> {{for people()}} <li> {{: first() }} </li> {{/for}} </script> <hr/> <ul data-bind="template: { name: 'peopleList2', foreach: people }"></ul> <script type="text/html" id="peopleList2"> <li> {{: first() }} </li> </script> <hr/> <ul data-bind="template: { name: 'peopleList3', foreach: people }"></ul> <script type="text/html" id="peopleList3"> <li> <input data-bind="value: first" /> <a href="#" data-bind="click: $root.removePerson"> x </a> </li> </script> <hr/> <button data-bind="click: addPerson">Add</button>
//jsRender engine starting here (function(ko, jsviews, $) { if (jsviews || $.views) { ko.jsRenderEngine = function() { //if no jQuery, then need to use jsviews var compiler = jsviews ? jsviews.templates : $.templates, views = jsviews ? jsviews : $.views; //save off the compiled template and render this.renderTemplateSource = function(templateSource, bindingContext) { var compiled = templateSource.data("compiled"); if (!compiled) { compiled = compiler(templateSource.text() || ""); templateSource.data("compiled", compiled); } return ko.utils.parseHtmlFragment(compiled.render(bindingContext.$data, { koBindingContext: bindingContext })); }; //ko adds code to hook up bindings after rendering this.createJavaScriptEvaluatorBlock = function(script) { return "{{:~ko_with(\"" + script + "\") }}"; }; //ko expects to be able to find the variables directly views.helpers({ ko_with: function(script) { var wrapped = "with(context) { with(data) { return " + script + "} }"; return (new Function("context", "data", wrapped))(this.ctx.koBindingContext, this.data); } }); }; ko.jsRenderEngine.prototype = new ko.templateEngine(); //set the default engine to be the jsRender engine ko.setTemplateEngine(new ko.jsRenderEngine()); } })(ko, this.jsviews, this.jQuery); //end jsRender engine //View Model code var Person = function(first, last, age) { this.first = ko.observable(first); this.last = ko.observable(last); this.age = ko.observable(age); }; var ViewModel = function() { var self = this; this.message = ko.observable("hello"); this.people = ko.observableArray([ new Person("Bob", "Smith", 30), new Person("Jim", "Jones", 22), new Person("Sally", "Johnson", 41) ]); this.addPerson = function() { self.people.push(new Person("new", "person", 0)); }; this.removePerson = function(person) { self.people.remove(person); }; }; ko.applyBindings(new ViewModel());
-----------------------------------
http://www.cnblogs.com/rock_chen/