Adding a function to a JavaScript object - javascript

In my JavaScript I have an object instance called "View". I want to add a function to this object. The function looks something like
function csiSelectValueRestriction (columnName) {
//... <a rather long and involved function>
}
Ultimately I want to be able to use the function in the following way:
var result = View.csiSelectValueRestriction ("bldgs");
What is the simplest way to accomplish this?

Just assign the function to the property;
View.csiSelectValueRestriction = csiSelectValueRestriction;

This should work if you want to add a function to an existing instance
View['csiSelectValueRestriction'] = function (columnName) { ... ... }

var View = {
someProperty: 'someVal',
csiSelectValueRestriction: function(columnName) {
//JS logic
}
};
or View.csiSelectValueRestriction = function(columnName) { ... }

Related

Pass function through x-tag accessors

I am trying to use x-tag accessors but I'm not finding a good documentation about them.I would like to pass a function through an accessor and write something like this:
<my-element logic="myFunction()"></my-element>
And I want to save that function and use it later. Is there any way to do that?
I'm really not sure what you're trying to accomplish, but I'll give it a shot. If you are trying to make some logic available on all <my-element> tags, use the methods object, like this:
xtag.register('my-element', {
methods: {
logic: function (a) {
return a * 2;
}
}
});
If you want to be able to assign logic to each instance of <my-element> individually, then you could use a standard (non-attribute) accessor, and do so implicitly.
xtag.register('my-element', {
accessors: {
logic: {}
}
});
HTML
<my-element id="test"></my-element>
Set logic for one instance of <my-element>
var el = document.querySelector('my-element#test');
el.logic = function (a) {
return a * 2;
};
If you want to use an attribute to set the value of logic to a global function, you could do this:
Example global function
function myFunction(a) {
return a * 2;
}
Component
xtag.register('my-element', {
accessors: {
logic: {
attribute: {},
get: function () {
return this._logic;
},
set: function (v) {
this._logic = window[v] || null;
}
}
}
});
Usage (HTML)
<my-element logic="myFunction"></my-element>
Usage (JS)
var el = document.querySelector('my-element');
el.logic(2); // 4

attache function to other function in javascript

I have a simple requirement, I need add the same code to hundreds of other JavaScript functions, the code can be executed at the end of the function, is there a handy way of doing it, like attach an function to another function dynamically, I think yes, because JavaScript is so powerful and too powerful, any ideas?
Note, I need dynamically assign new code or function to existing functions without change existing function's code, please give a solid solution, I can do it in hacky way, but no hacky way please!
The first method that comes to mind is simply create another function:
function primaryFunction() {
// ...
utilityMethod();
}
function otherPrimaryFunction() {
// ...
utilityMethod();
}
function utilityMethod() { ... }
Now utilityMethod() gets called from the end of each other primary function.
There's also a method which requires more code refactoring but is better in the long term: classes/prototypes.
Essentially, you have one "constructor" function which takes a number of parameters for the "class" and returns an class-like object:
function constructor(someClassField, anotherField) {
this.aField = someClassField;
this.fieldTwo = anotherField;
return this;
}
Now if you call this and pass some parameters, you get a class out:
var myClass = new constructor("1", "2");
myClass.aField == "1";
myClass.fieldTwo == "2";
So: If you define your utility method as above, then you can use this: for every primary function you instantiate a new instance of the constructor, with the final code looking like this:
function constructor(primaryFunction) {
this.function = primaryFunction;
this.call = function() {
this.function();
utilityMethod();
}
this.call();
return this;
}
function utilityMethod() { ... }
var primaryMethod = new constructor(function() { ... });
The creation of primaryMethod now automatically calls the primary function followed by the utility method, before returning the object so you can re-call both if you want to.

Add my own function to Slickgrid DataView

I would like extends the Slickgrid DateView to add a getter for the filterArgs, see https://github.com/mleibman/SlickGrid/pull/775/files.
Example of wrong code... :
(function($) {
$.extend(Slick.Data.DataView, {
"getFilterArgs": function getFilterArgs() {
return filterArgs;
}
});
})(jQuery);
Do you know the right way? Thanks
It seems for me that the only possible way to fit your requirements is to use your own setter as well. Something like:
Extend DataView class with a new getFilterArgs method:
Slick.Data.DataView.prototype.getFilterArgs = function () {
return this._filterArgs;
}
Create your own setFilterArgsInternal method and use it:
Slick.Data.DataView.prototype.setFilterArgsInternal = function (args) {
this.setFilterArgs.call(this, args);
this._filterArgs = args;
}
Again, everywhere after that use setFilterArgsInternal instead of setFilterArgs.

Javascript convert string to be called as function

I have the following scenario where I need to call a function based on the data attributes of the html element.
function func1(arg1){
alert("func1");
}
function func2(arg2){
alert("func2");
}
jQuery(document).on('click', '.func-class', function(){
var funcName = jQuery(this).data('func-name');
var funcArg = jQuery(this).data('func-arg');
//Need to call funcName(funcArg) here
});
HTML:
<div data-func-name="func1" data-func-arg="arg1" class="func-class">Func1</div>
<div data-func-name="func2" data-func-arg="arg2" class="func-class">Func2</div>
JSFiddle of the same:
http://jsfiddle.net/E4HeT/
If those functions are defined in ths global scope, you can do this:
window[funcName](funcArg);
Otherwise, I would suggest putting them in an object like so:
var functions = {
"func1":func1,
"func2":func2
};
functions[funcName](funcArg);
This second one is actually safer, as it helps prevent arbitrary code execution.
you can do like the following this
window[funcName](funcArg)
but you will have to get the reference of the function by setting it in a object for example (like what i did in the window object) because its private in the jQuery.ready function
$('.func-class').click(function(){
var toCallArg = $(this).data('func-arg');
var toCall = function(toCallArg){
//your code
};
toCall(toCallArg);
});

JavaScript object is undefined

I need some help please with a javascript object. it goes like this:
I call this function addFilter(element) with a html DOM element.
The function looks like this:
function MyList() {
this.arr = new Array();
this.index = 0;
}
MyList.prototype.add = function(filter) {
this.arr[this.index++] = filter;
//alert(this.arr[0] + ' mylist arr');
}
function Filter(element) {
this.setElement(element);
}
Filter.prototype.setElement = function (element) {
this.element = element;
this.kinorid = $(element).attr('id');
}
function addFilter(element) {
filters.Add(new Filter(element));
}
var filters = new MyList();
Now with in another function that in my case the function creates the jquery UI Slider, and every time the slider changes i need to get the parent element of that element that was sent to addFilter like i said in the beginning. so then i try doing
var value = filters.arr[0];
but like i said it id undefined.
Can any one please help me by reviewing the code, and tell me whats wrong.
Thank you very much.
You still haven't said where or how you're using filters.arr[0], without which it's very difficult to help you.
Assuming your code using it looks something like this:
AddFilter($("#theElement"));
display(typeof filters.arr[0]);
filters.arr[0].element.css("color", "blue");
It should be working; live example.
My only thought is if AddFilter and filters are not defined within the same scope. You're using filters within AddFilter, so AddFilter must be defined in the same scope as filters (or in a sub-scope). So this would be fine:
var filters;
function AddFilter() { ... }
And this
function AddFilter() { ... }
var filters;
And this
var filters;
$(function() {
function AddFilter() { ... }
});
But not
function AddFilter() { ... }
$(function() {
var filters;
// ...
});
...because in that last case, AddFilter is defined outside the scope in which filters is defined.
Your code is very convoluted, I don't understand it at all. Anyway, you are looking for (I think):
var value = filters.arr[0].element;
since you assign the element reference to arr[this.index].
Incidentally, if you are passing an element, then:
$(this).attr('id');
is an awfully slow way to do:
this.id;
Edit
The code I used (where there was a div with id 'd0' in the DOM):
var filters = new MyList();
AddFilter(document.getElementById('d0'));
alert(filters.arr[0].element);

Categories