<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> #content1{padding: 20px;} </style> </head> <body> <div id="content1"> <div data-bind="component:'MessagerAndList'"></div> </div> <script src="scripts/jQuery183.js"></script> <script src="scripts/knockout30.js"></script> <script> $(function(){ ko.components.register( 'MessagerAndList',{ viewModel:function(){ var self = this; self.Account = ko.observable('tom'); self.MessageText = ko.observable(''); self.Send = function(){ self.MessageList.push({message:self.MessageText(),account:self.Account()}); self.MessageText(""); }; self.MessageList = ko.observableArray([]); }, template:'<input type="text" data-bind="value:MessageText" /><button id="Send" data-bind="click:Send" >發送</button><ul data-bind="foreach:MessageList"><li><p data-bind="html:message">文本內容1</p><b data-bind="html:account"></b></li></ul>' } ); ko.applyBindings(); }); </script> </body> </html>
做者能夠經過傳入參數改變:html
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style> #content1{padding: 20px;} </style> </head> <body> <div id="content1"> <div data-bind="component:{name:'MessagerAndList',params:'jerry'}"></div> </div> <script src="scripts/jQuery183.js"></script> <script src="scripts/knockout30.js"></script> <script> $(function(){ ko.components.register( 'MessagerAndList',{ viewModel:function(params){ var self = this; self.Account = ko.observable(params != null ? params:"tom"); self.MessageText = ko.observable(''); self.Send = function(){ self.MessageList.push({message:self.MessageText(),account:self.Account()}); self.MessageText(""); }; self.MessageList = ko.observableArray([]); }, template:'<input type="text" data-bind="value:MessageText" /><button id="Send" data-bind="click:Send" >發送</button><ul data-bind="foreach:MessageList"><li><p data-bind="html:message">文本內容1</p><b data-bind="html:account"></b></li></ul>' } ); ko.applyBindings(); }); </script> </body> </html>