1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- <html>
- <head>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
- <script src="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.1.6/zepto.min.js"></script>
- <script src="../lib/php_crud_api_transform.js"></script>
- <script id="posts-template" type="text/html">
- <ul>
- <!-- ko foreach: posts -->
- <li>
- <span data-bind="text: id"></span>, <span data-bind="text: content"></span>
- <a href="javascript:void(0)" data-bind="click: $parent.edit">edit</a>
- <a href="javascript:void(0)" data-bind="click: $parent.delete">del</a>
- </li>
- <!-- /ko -->
- <li>
- <form data-bind="submit: submit">
- <input name="content" data-bind="value: form"/>
- </form>
- </li>
- </ul>
- </script>
- <script>
- var url = '../api.php/posts';
- function Post(id,content){
- var self = this;
- self.id = ko.observable(id);
- self.content = ko.observable(content);
- }
- function PostList(){
- var self = this;
- self.posts = ko.observableArray([]);
- self.form = ko.observable('');
- self.bound = false;
- self.edit = function(post) {
- var content = prompt('Value',post.content());
- if (content!==null) {
- $.ajax({url:url+'/'+post.id(), type: 'PUT', data: {content:content}, success:self.update});
- }
- };
- self.delete = function(post) {
- if (confirm("Deleting #"+post.id()+". Continue?")) {
- $.ajax({url:url+'/'+post.id(), type: 'DELETE', success:self.update});
- }
- };
- self.submit = function(form) {
- $.post(url, {user_id:1,category_id:1,content:self.form()}, self.update);
- };
- self.render = function(data) {
- var array = php_crud_api_transform(data).posts;
- self.posts.removeAll();
- for (i=0;i<array.length;i++) {
- self.posts.push(new Post(array[i].id,array[i].content));
- }
- self.form('');
- if (!self.bound){ ko.applyBindings(self); self.bound = true; }
- };
- self.update = function() {
- $.get(url, self.render);
- };
- self.post = function() {
- $.post(url, {user_id:1,category_id:1,content:"from knockout"}, self.update);
- }
- self.post();
- };
- $(function(){ new PostList(); });
- </script>
- </head>
- <body>
- <div data-bind="template: { name: 'posts-template'}">Loading...</div>
- </body>
- </html>
|