,我創建了一個下拉菜單來顯示用戶鍵入的國家/地區列表。現在,他們可以選擇一個,點擊'sublit'然後通過流星調用插入到我的Posts集合中。下面的代碼以及這個jQuery代碼(保存在客戶端文件夾中)可以讓這個功能起作用。使用的輸入ID是「國家」。流星:允許預定值在我的表單中輸入集合
https://github.com/twitter/typeahead.js/blob/master/dist/typeahead.jquery.js
我的目標:要只允許在我的「國家」變量中列出的國家將被插入到數據庫中。我希望在我的方法函數中對其進行驗證。
CLIENT:
Template.createpost.rendered = function() {
if (!this.rendered){
var substringMatcher = function(strs) {
return function findMatches(q, cb) {
var matches, substrRegex;
matches = [];
substrRegex = new RegExp(q, 'i');
$.each(strs, function(i, str) {
if (substrRegex.test(str)) {
matches.push({ value: str });
}
});
cb(matches);
};
};
var country = [
"Afghanistan",
"Albania",
"Algeria",
"Andorra",
"Angola",
"Antigua and Barbuda",
"Argentina",
"Rest Of Countries"
];
$('#country').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'country',
displayKey: 'value',
source: substringMatcher(country)
});
this.rendered = true;
}
};
Template.createpost.events({
'submit form#createpost': function(e, tmpl) {
e.preventDefault();
var insertPostData = {
country: $(e.target).find('#country').val()
}
Meteor.call('insertPostData', insertPostData, function(error, id){
if (error) {
alert(error.reason);
}
});
}
});
服務器:我的方法到目前爲止只會在用戶沒有選擇國家時拋出錯誤。我不確定使用語法來檢查從客戶端接收的國家/地區值與我希望在我的方法中列出的值的數組的關係我接受其他建議以實現此目的,請讓我知道。感謝你們。
Meteor.methods({
'insertPostData': function(insertPostData){
if (!insertPostData.country)
throw new Meteor.Error(422, 'please select valid country');
return insertPostData._id = AllPosts.insert(insertPostData);
}});
看看[Collection2](https://github.com/aldeed) /流星collection2)! – richsilv 2014-10-02 10:17:04