Passing parameters on JQuery .trigger - javascript

I am using JQuery trigger but am not sure what the correct syntax is to pass parameters in my situation. Here is where I am making the call :
$('#'+controlName).trigger(event);
Here is where I am doing the event binding :
$(window).on('onPartialRendered', onPartialRendered);
And here is my event handler :
var onPartialRendered = function () {
.....
};
Everything works fine until I try to pass parameters. What would be the correct way to do it as per my example?

First parameter is always string with event name and next parameters are additional data:
.trigger('foo', [1, 2]);
.on('foo', function(event, one, two) { ... });
Special thanks for Rocket Hazmat
Example:
var controller = {
listen: function (event, json, string) {}
};
$('body').trigger('this_works', [{data: [1, 2, 3]}, 'something']);
$('body').on('this_works', function (event, json, string) {
controller.listen(event, json, string);
});
Remote partial:
Please do not use this way. There is many article about this problem in network. This take much time and generate unnecessary traffic in network. Please use this way:
var template = $('#templates #example_template').detach();
var clone = template.clone();
clone.find('.some_field').val('new_data');
clone.attr('id', null);
$('table tbody').append(clone);

Related

javascript send object's attributes to function

i have a situation i have been thinking for a while and cant seem to find logic to solve it. hope you can.
i have a series of buttons that i would like to track, an example of one is this:
when a button is clicked a function is called, sending some strings and an object with a series of attributes. different buttons have different sets of attributes.
$(".btn").on('click', function(ev){
trackFunction("Purchase","apply_promo", { product_code: "product1", last_page: "home", refer: "facebook", promo: "12345" });
});
The track function will then receive this and send it to my analytics software
but i need it to be sent in this format
dataToSend = { event_type : eventType, event_value: eventValue, data };
where data is each and every attribute from the object the button is sending.
in that example it woud be something like this
dataToSend = { event_type : eventType, event_value: eventValue, data.product_code, data.last_page, data.refer, data.promo };`
here is my tracking function :
function trackFunction(eventType, eventValue, data ) {
dataToSend = { event_type : eventType, event_value: eventValue, data };
analyze(dataToSend);
return true;
}
the problem here is that not every button is sending the same attributes inside the object so i cant hardcode the output.
hope i made myself clear.
and thank you so much.
Either you add the common properties to the object each time. The downside is that you're altering a function parameter which is generally a bad idea because it might cause weird bugs:
function track(a, b, data) {
data.a = a;
data.b = b;
sendData(data);
}
Or you turn it around by iterating over the object's properties:
function track(a, b, data) {
var send = {a: a, b: b}, k;
for (k in data) {
if (data.hasOwnProperty(k)) {
send[k] = data[k];
}
}
sendData(send);
}
If you use lodash, underscore, or jQuery (or probably every other JS framework out there) you usually have an extend function at your disposal, which does pretty much what you want (and internally the same as the second example).
// with underscore:
function track(a, b, data) {
sendData(_.extend({a: a, b: b}, data));
}

GoJS: use more than one parameter in a conversion function

I need to use two properties of a node in GoJS to perform a particular operation. Here is my current code:
$(go.Picture,
{
//some properties
},
new go.Binding("source", "item_status", getIcon)),
//....
function getIcon(item_status) {
//do something
}
Is it possible to modify the above code so that getIcon() function gets a second parameter called item_id? E.g can i do something like this:
new go.Binding("source", "item_status","item_id", getIcon)),
....
function getIcon(item_status, item_id) {}
Thanks
Answering my own question again...
to get all data for a particular node, you can pass "" instead of "item_status" to the Binding function.
go.Binding("source", "", getIcon)),
...
getIcon(node){
var x = node.item_status;
var y = node.key;
}

TAFFYdb: Passing in options to a function

update: This code is bonkers. The root of the issue here is recreating the name of a variable by concating strings and assuming it would then magically turn into that variable.. I had a lot to learn. Also, a much better way to pass an ambiguous number of options into a function is to use JSON.
var availableTimes,
selected_unit,
selected_unit_number;
function createTimePicker(machineNumber){
availableTimes = machineNumber({booked:"no"}).select("time");
for (i=0;i<availableTimes.length;i++){
$('<option/>').val(availableTimes[i]).html(availableTimes[i]).appendTo('#signin_start_time');
}
}
$(function() {
$('body').on('click', '#cybex_arctrainer_button', function() {
selected_unit = "cybex_arctrainer";
});
$('body').on('change', '#signin_unit_number_selector', function () {
selected_unit_number = $("#signin_unit_number_selector option:selected").text();
unit_plus_number = selected_unit+selected_unit_number;
createTimePicker(unit_plus_number);
});
});
A few things: The database works. If I run createTimePicker(cybex_arctrainer1) it fills in the availableTimes variable just fine. The problem seems to be with combining selected_unit+selected_unit_number and passing them to createTimePicker.
Here:
machineNumber({booked:"no"})
machineNumber is a string, but you're trying to call it as if it is a function. You'll get the same error if you do something like
someVar = 'bob';
someVar();
You say that if you run
createTimePicker(cybex_arctrainer1);
but your code is not calling createTimePicker with the variable cybex_arctrainer1 as an argument, instead it's doing something more like:
createTimePicker('cybex_arctrainer1');

How can I provide a public function in a jQuery plugin?

I have written a small jQuery plugin with the following structure:
(function($) {
// Private vars
// Default settings
$.PLUGINNAME = {
id: 'PLUGINNAME',
version: '1.0',
defaults: {
min: 0,
max: 10
}
};
// extend jQuery
$.fn.extend({
PLUGINNAME: function(_settings) {
init = function() {
}
prepare = function() {
}
...
return this.each(function() {
_this = this;
init();
});
}
});
})(jQuery);
I am calling this as follows:
$("#update-panel").PLUGINNAME({
min: 1,
max: 20
});
I am trying to provide an additional public method where some data inside the function can be updated after the above function call to the plugin and am not sure how to go about doing this. What I am looking for is something like this:
_PluginInstance = $("#update-panel").PLUGINNAME({
min: 1,
max: 20
});
...
...
_PluginInstance.setMin(2); //should change the minimum to 2
setMin will probably use some of the plugin's internal variables so I am not understanding how to do this. I know I am not returning an instance of the plugin to do the above but can someone please tell me how to go about doing this by keeping the same plugin structure?
Just make the function a property of this within the PLUGINNAME object:
(function($) {
$.PLUGINNAME = {
// Default settings
};
// extend jQuery
$.fn.extend({
PLUGINNAME: function(_settings) {
// private methods
var init = function() {};
var prepare = function() {};
// public methods
this.setMin = function ( val ) {
_settings.min = val;
};
this.getMin = function () {
return _settings.min;
};
return this.each(function() {
_this = this;
init();
});
}
});
})(jQuery);
Then you could do:
_PluginInstance = $("#update-panel").PLUGINNAME({
min: 1,
max: 20
});
_PluginInstance.getMin(); // 1
_PluginInstance.setMin(2);
_PluginInstance.getMin(); // 2
EDIT: Oh god I can't believe I forgot the var keywords, why didn't y'all tell me my fly was down?
You could use the jQuery-UI method calling style:
$("#update-panel").PLUGINNAME('method', arguments...);
And then in your plugin:
PLUGINNAME: function(_settings, args) {
if(!$.isPlainObject(_settings)) {
// _settings (should) be the method name so
// do what needs to be done to execute the method.
return;
}
// Proceed as before.
You might want to use the arguments pseudo-array instead of the extra args parameter. You can store extra things in $(this).data('PLUGINNAME') inside your PLUGINNAME function if you need to attach internal data to your individual objects.
Not a jQuery guy myself, and mu is too short's answer seems to be the right one. But I'd imagine you could also do like it says on jQuery's own docs and use the .data() method to store the min/max values.
In other words, make your code look for existing data on the elements, so the first time you call $('#update_panel').plugin({min:1, max:20}), it won't find any existing data, so it'll place those min/max values in an object and "save" them using .data().
Then, when you later call $('#update_panel').plugin({min:2}) your code finds the existing data, and updates the values.
Just an idea
You can define a variable just like you've defined a plugin.
$.fn.PLUGINNAME.someVariable = 4;
or if you prefer, just declare an empty variable outside the plugin and then add to it from inside the plugin
var someVariable;
(function($) {
... the plugin code
})(jQuery);

Javascript: How change function call params on the fly?

I'm receiving some 'body' content from a jquery's json call, where I can get the unique javascript element returned by doing:
script_element = $(data.body)[1]
This equals to:
<script type=​"text/​javascript">​
updater('foo', 'bar', {}, '0', constant='');
</script>​
So, typeof script_element returns "object"
And, if I run script_element.innerText, I can get:
updater('foo', 'bar', {}, '0', constant='');
After receiving this script, what I'm doing right now is just run an eval on it, but searching around I couldn't get a way to run eval changing function call params.
What I'm trying to do is change the third param of the call, in this case the {}, that can change depending on the return of the json call, so I can't just search for {}.
I could also do script_element.text.split(',')[2] for example, and change this text on the fly, but I was thinking there should be a better way to do this.
I don't know if javascript can recognize and treat a "future method call", but still think there should be a better way.
Any idea?
What you could do is shadowing the function so as to be able to alter the third argument. You ought to define that shadowing function before fetching the JSON.
var originalUpdater = updater; // keep old function to call
// overwrite (shadowing)
updater = function(a, b, c, d, e) {
// change c appropriately here
originalUpdater(a, b, c, d, e);
}
Then you can still just eval it (which is not very safe, but that's not your point if I'm not mistaking), and it will call the shadow function.
A more generic shadowing method would be along the lines of:
var originalUpdater = updater; // keep old function to call
// overwrite (shadowing)
updater = function() {
// change arguments[2] appropriately here
originalUpdater.apply(this, arguments);
}
Fiddle: http://jsfiddle.net/n7dLX/
Change the server. Rather than returning
<script type=​"text/​javascript">​
updater('foo', 'bar', {}, '0', constant='');
</script>​
Return
{
"method": "updater",
"params": [
"foo", "bar", {}, "0", ''
]
}
Assuming that you cannot change what is being sent over from the server, you can simply run through the innerText with a regular expression and pass update the HTML before you insert it.
var replacer = /\w+\(([^()]+)\)/gi;
script_element.innerText.replace(replacer, function(matched_text, func_params){
var orig_func_params = func_params;
// Make changes to func_params here.
return matched_text.replace(orig_func_params, func_params);
});
This can be functionized by doing the following:
var replacer = /\w+\(([^()]+)\)/gi;
function replace_arg(script_element, arg_index, replacement_value) {
script_element.innerHTML = script_element.innerHTML.replace(replacer,
function(matched_text, func_params){
var orig_func_params = func_params;
func_params = func_params.split(",");
if (arg_index >= func_params.length) {
throw new RangeError(arg_index + " is out of range. Total args in function:" + func_params.length);
}
func_params[arg_index] = JSON.stringify(replacement_value);
return matched_text.replace(orig_func_params, func_params.join(","));
});
return script_element;
}
This can be called in this way:
script_element = replace_arg(script_element, 3, {"new":"arg"});
I don't understand what you are doing, but in general if you don't want to rely on the order of parameters make the function take one parameter that is an object whose properties are the parameters:
function add(params) {
var a = params.hasOwnProperty("paramA") ? params.paramA : 0;
var b = params.hasOwnProperty("paramB") ? params.paramB : 0;
return a + b;
}
add({paramA: 1, paramB: 2});
In this case you should use hasOwnProperty to check if the function was passed the parameter you are looking for before trying to access it.

Categories

Resources