Revision a82f3bef
Von Moritz Bunkus vor etwa 11 Jahren hinzugefügt
js/kivi.js | ||
---|---|---|
99 | 99 |
|
100 | 100 |
return true; |
101 | 101 |
}; |
102 |
|
|
103 |
// Run code only once for each matched element |
|
104 |
// |
|
105 |
// This allows running the function 'code' exactly once for each |
|
106 |
// element that matches 'selector'. This is achieved by storing the |
|
107 |
// state with jQuery's 'data' function. The 'identification' is |
|
108 |
// required for differentiating unambiguously so that different code |
|
109 |
// functions can still be run on the same elements. |
|
110 |
// |
|
111 |
// 'code' can be either a function or the name of one. It must |
|
112 |
// resolve to a function that receives the jQueryfied element as its |
|
113 |
// sole argument. |
|
114 |
// |
|
115 |
// Returns nothing. |
|
116 |
ns.run_once_for = function(selector, identification, code) { |
|
117 |
var attr_name = 'data-run-once-for-' + identification.toLowerCase().replace(/[^a-z]+/g, '-'); |
|
118 |
var fn = typeof code === 'function' ? code : ns.get_function_by_name(code); |
|
119 |
if (!fn) { |
|
120 |
console.error('kivi.run_once_for(..., "' + code + '"): No function by that name found'); |
|
121 |
return; |
|
122 |
} |
|
123 |
|
|
124 |
$(selector).filter(function() { return $(this).data(attr_name) != true; }).each(function(idx, elt) { |
|
125 |
var $elt = $(elt); |
|
126 |
$elt.data(attr_name, true); |
|
127 |
fn($elt); |
|
128 |
}); |
|
129 |
}; |
|
130 |
|
|
131 |
// Run a function by its name passing it some arguments |
|
132 |
// |
|
133 |
// This is a function useful mainly for the ClientJS functionality. |
|
134 |
// It finds a function by its name and then executes it on an empty |
|
135 |
// object passing the elements in 'args' (an array) as the function |
|
136 |
// parameters retuning its result. |
|
137 |
// |
|
138 |
// Logs an error to the console and returns 'undefined' if the |
|
139 |
// function cannot be found. |
|
140 |
ns.run = function(function_name, args) { |
|
141 |
var fn = ns.get_function_by_name(function_name); |
|
142 |
if (fn) |
|
143 |
return fn.apply({}, args); |
|
144 |
|
|
145 |
console.error('kivi.run("' + function_name + '"): No function by that name found'); |
|
146 |
return undefined; |
|
147 |
}; |
|
102 | 148 |
}); |
103 | 149 |
|
104 | 150 |
kivi = namespace('kivi'); |
Auch abrufbar als: Unified diff
ClientJS: neue Funktionen "run()", "run_once_for()"; Dokumentation