在jQuery中调用knockout viewmodel函数
如何在jQuery函数中调用viewmodel函数? 我只想从Javascript函数调用viewmodel函数的函数。
function ContactsViewModel(data) { var self = this; // Editable data self.Contacts = ko.observableArray(JSON.parse(data)); self.limit = ko.observable(20); self.changeNumber = function(item){ self.limit(self.limit()+20); self.Contacts.push(item); } self.myPostProcessingLogic = function(elements) { if ($('#KnockOutContacts').children().length === ko.toJS(self.Contacts).length) { // Only now execute handler jq(); } } }
如何从jscroll
窗格函数调用changeNumber
?
$('.jspScrollable').bind( 'jsp-arrow-change', function(event, isAtTop, isAtBottom, isAtLeft, isAtRight) { // Now look at the is* parameters and do what you // need to do. All four of the is* parameters are booleans. if(isAtBottom) { ContactsViewModel.changeNumber(); } } );
数据来自服务器
function returnData(url,data,type){ $.post(url, data, function(returnedData) { if(type == "contacts") { ko.applyBindings(new ContactsViewModel(returnedData),$("#KnockOutContacts")[0]); } else if(type == "logs") { ko.applyBindings(new LogsViewModel(returnedData),$("#KnockOutLogs")[0]); } else if(type == "sms") { ko.applyBindings(new SmsViewModel(returnedData,"#KnockOutSms"),$("#KnockOutSms")[0]); ko.applyBindings(new SmsViewModel(returnedData,"#KnockOutSmsData"),$("#KnockOutSmsData")[0]); } }); }
提前致谢。
我同意Anders关于使用自定义绑定的看法。 但如果您真的想要,请尝试从您的ContactsViewModel返回’self’(参见下面的示例)
function ContactsViewModel(data) { var self = this; // Editable data self.Contacts = ko.observableArray(JSON.parse(data)); self.limit = ko.observable(20); self.changeNumber = function(item){ self.limit(self.limit()+20); self.Contacts.push(item); } self.myPostProcessingLogic = function(elements) { if ($('#KnockOutContacts').children().length === ko.toJS(self.Contacts).length) { // Only now execute handler jq(); } } //return self return self; } //Variable you'll use to reference in jQuery var myVm = ContactsViewModel(yourdata); ko.applyBindings(myVm); myVm.changeNumber(yourItem);
创建一个挂钩jQuery东西的自定义绑定。 你的viewmodels中永远不应该有任何与DOM相关的代码作为反模式。
像(不工作的代码)
ko.bindingHandlers.scrollable = { init: function(element, valueAccessor) { var onScroll = valueAccessor(); $(element).bind( 'jsp-arrow-change', function(event, isAtTop, isAtBottom, isAtLeft, isAtRight) { // Now look at the is* parameters and do what you // need to do. All four of the is* parameters are booleans. if(isAtBottom) { onScroll(); } }); } };
从您的观点中使用过
你可以这样做:
视图模型
var searchViewModel = function () { var self = this; self.search = function (param) { //do something }; }
HTML
jQuery的
function Search() { // paramvalue = 1; viewModel.search(paramvalue); }