Problem with declaring callbacks in the data-* attributes
See original GitHub issueWhat I like about select2 is the idea to specify all configuration parameters in data-* attributes.
Suppose I have some sort of templating function stored in my namespace:
window.myNamespace = {
templateResult: function(item) {
if (item.loading) return item.text;
return '<div>' + item.text + ' (' + item.price + ')' + '</div>';
}
}
Now I want to specify this function as a callback in my select tag in data-template-result attribute like that:
<select class="select2" data-template-result="myNamespace.templateResult"></select>
Clean and cool but does not work. The reason is, as we can read from the Jquery docs: “Every attempt is made to convert the string to a JavaScript value (this includes booleans, numbers, objects, arrays, and null)”. No function in this list. So, now there is no legal way to declare callbacks using data-* attributes.
For now I’m using the following workaround: I’m prefixing all my callback names with ‘_fn::’ like this: “_fn::myNamespace.templateResult”. Then, before activating any select tag with select2(), I’m using the following function to let jQuery know about callbacks declared in data-* attributes:
function(obj) {
var getFunctionByName = function (functionName, context) {
context = typeof context === 'undefined' ? window : context;
var namespaces = functionName.split(".");
var func = namespaces.pop();
for(var i = 0; i < namespaces.length; i++) {
context = context[namespaces[i]];
}
return context[func];
}
var $obj = $(obj);
$.each($obj.data(), function(key, el) {
if (typeof el === 'string' && el.substr(0, 5) == '_fn::') {
$obj.data(key, getFunctionByName(el.substr(5)));
}
});
}
Works just fine, but looks like a hack.
Maybe we can do something with select2 behavior itself to let users legally specify callbacks in data attributes without using such external hacks?
Issue Analytics
- State:
- Created 9 years ago
- Reactions:3
- Comments:8 (2 by maintainers)
This is still an issue and a simple fix like one of the suggestions would be fantastic in the next release. Is it possible to revisit, there are existing PRs (closed) that would address the issue.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.