[英]how to update the source of x-editable of select2 type
這是我正在嘗試的http://jsfiddle.net/wQysh/347/
JS:
$.fn.editable.defaults.mode = 'inline';
var count = 4, sources = [];
for(var i = 1; i <= count; i++){
sources.push({ id : i, text : 's-'+String(i) })
}
var getSource = function() {
//i want this function must be called whenever available options is rendred. to ensure NO references issues, i used JSON.parse
return JSON.parse(JSON.stringify(sources));
};
var getQuery = function(options){
options.callback({ results : getSource() });
};
var getInitSel = function(multiple) {
return function(el, cb){
var t, toSet = [], sc = getSource();
el[0].value.split(',').forEach(function(a){
t = _.findWhere(sc, { id : Number(a.trim()) });
if(t) toSet.push(t);
});
cb(multiple ? toSet : (toSet.length ? toSet[0] : null));
};
};
$('#controller').click(function(e){
count++;
sources.push( {id : count, text : 's-'+String(count) });
$('#username').editable('option', 'source', getSource()); // <---------------- THIS LINE HAS NO EFFECT SO PRODUCING UNDESIRED RESULT
//with above line, the source option should get updated and should be handing the new records to render. but nothing happens such.
$('#username').editable('setValue', [1, count]);
});
$('#username').editable({ //to keep track of selected values in multi select
type: 'select2',
url: '/post',
autotext : 'always',
source : getSource(),
value : [1,2],
emptytext: 'None',
select2: {
multiple : true,
initSelection : getInitSel(true),
query :getQuery
}
});
//ajax emulation. Type "err" to see error message
$.mockjax({
url: '/post',
responseTime: 400,
response: function(settings) {
if(settings.data.value == 'err') {
this.status = 500;
this.responseText = 'Validation error!';
} else {
this.responseText = '';
}
}
});
我只是想通過控制器更新可編輯元素的源選項。 但是視圖並不能反映出相同的觀點。
任何解決方案?
剛剛添加了顯示功能,iDkey為“ id”
$('#username').editable({ //to keep track of selected values in multi select
type: 'select2',
url: '/post',
autotext : 'always',
source : getSource(),
value : [1,2],
emptytext: 'None',
display: function(value, sourceData) {
//display checklist as comma-separated values
var html = [],
checked = $.fn.editableutils.itemsByValue(value, getSource(), 'id'); // it was needed to send 'id' as idKey otherwise it was fetching with value
if(checked.length) {
$.each(checked, function(i, v) { html.push($.fn.editableutils.escape(v.text)); });
$(this).html(html.join(', '));
} else {
$(this).empty();
}
},
select2: {
multiple : true,
initSelection : getInitSel(true),
query :getQuery
}
});
這是工作代碼http://jsfiddle.net/wQysh/351/
每當我們將“ setValue”設置為可編輯時,或在關閉事件時,都會調用可編輯的“顯示”功能。
在顯示功能中,此功能會檢查現有值
$.fn.editableutils.itemsByValue
其中第三個參數接受idKey。 如果在調用此函數時未提供第三個參數,則默認情況下它將“值”作為idKey。 當我們用來加載數組數據時,不應使用'value'作為idKey。 參考: http : //ivaynberg.github.io/select2/#data_array 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.