how can i change property defined in object constructor javascript - javascript

if i have the below code , how can i change the isHTML property at any time while the application running ,i have tried the below and tried many javascript access ways and it fails also.
obj = new ss({
something: {
ishtml: myfunction(true),
},
});
document.getElementbyId("#id").onclick = function() {
myfunction(false);
}
function myfunction(bool) {
return bool;
}
after all of that when i use the application again it uses the intial values i send via the function

Related

How to use Callback functions in Class with JavaScript/jQuery

I have a class I am using for creating CRUD Objects for my site.
It stores the form and table paths for adding, listing, editing and deleting the data, as well as reloading your view with ajax after each edit.
Here is my class definitions:
class CRUDObj{
constructor(containerSel, links) {
this.links = links;
this.containerSel = containerSel;
this.formCallBack = function(){};
}
setActive(obj_id){
$.post(this.links.editURL+'?'+obj_id, {status:"active"}, this.reload);
}
reload(returnData){
this.formCallBack(returnData);
this.formCallBack = function(){};
if($(this.containerSel).length > 0){
ajaxLoad(this.links.listURL, $(this.containerSel));
}
}
}
A basic instance of initializing it:
var contactObj = new CRUDObj('#contacts', {
editURL: '/contact.edit.php',
listURL: '/contacts.list.php',
});
contactObj.formCallBack = function(){
console.log('Custom Reload Callback');
};
The problem appeared when I tried to add the callback, so that I could run a custom function during the refresh.
Running contactObj.setActive(); works properly, and my refresh function is called after the form submits, but when it hits my callback I get:
Uncaught TypeError: this.formCallBack is not a function
Calling it manually contactObj.refresh(); works smoothly.
How can I pass this callback function through better?
The problem is that you're passing method as function, so you loose this context. this will be window object or undefined (if using strict mode):
You need this:
var self = this;
lightboxForm(this.links.editURL+'?'+obj_id, function(x) { self.reload(x) });
or using ES6
lightboxForm(this.links.editURL+'?'+obj_id, x => this.reload(x));
or using bind to return function with given context:
lightboxForm(this.links.editURL+'?'+obj_id, this.reload.bind(this));

Can you set a function inside an object in chrome.storage.local?

Im building a chrome app and I am trying to add a function inside an object inside chrome.storage.local but when im doing it it does not appear if you try to get it (all the other things appear but not the function)
But if you try to do it on a normal object like
let a = {
b: function() {
return 'This is working'
}
};
then it works.
It wouldn't be a problem if I could just use eval but due to security on the chrome app it does not work.
What im trying to do is:
chrome.storage.local.set({
'obj': [{
example: 'hello',
fn: function() {
return 'This is not working'
}
}]
});
Then if you do
chrome.storage.local.get('obj', function(e) {
console.log(e.obj)
});
Then it will return with
Array (length 1): example: "hello"
and not the function,
Thanks.
Store arguments and the body like this
{function:{arguments:"a,b,c",body:"return a*b+c;"}}
Retrieve it and instantiate the function:
let f = new Function(function.arguments, function.body);

Google Chrome - Watch when javascript object property changes [duplicate]

This question already has answers here:
Breakpoint on property change
(8 answers)
Closed 5 years ago.
I have a JavaScript variable called
var someProperty;
on line, let's say 10000 (its a huge js file), I have a function
function updateTime() {
console.log(someProperty.time); //i actually get an value here
}
I want to find out the function that is changing the value of the property I tried setting breakpoint using Chrome dev tools directly on that var someProperty but received a value of "undefined" - which makes me believe a function is setting this variable. How can I find out or watch where this someProperty.time property is being set?
This is a possible solution
var someProp = {
time: 'give me'
};
Object.defineProperty(someProp, 'time', {
set: function(time) {
this.__time = time
console.log('Method1: Getting time from:',arguments.callee.caller)
},
get: function() {
return this.__time;
}
});
(function ILikeChanges() {
someProp.time = 'changes';
})()
Another modern solution would be to use a Proxy object to wrap your object, that will give you the ability to add listeners to updates to your object.
In the set function we are using console.trace to print a full stack trace which will direct you to the calling function.
MDN Proxy
const watchObject = obj => new Proxy(obj, {
set(target, key, value) {
console.trace('set', { key, value })
return target[key] = value
}
});
// wrap the object with our proxy
const someProperty = watchObject({ time: new Date })
function setTime() {
someProperty.time = new Date
}
// call the function that changes the state
setTime()
// look in your console for the call stack

Access extension's functions from webpage in Firefox

I'm trying to write an extension to Firefox that would allow me to access internal functions/classes/objects of it from my webpage. I want them to be visible and accesible in DOM. It worked when extension was loaded as a component from chrome.manifest file but it doesn't seem that it's possible in e10s (multiprocess Firefox) anymore.
So I was trying and trying and the best option I have found so far seems to be using exportFunction, createObjectIn and cloneInto functions. They work fine when expected to make objects visible from pages loaded by the extension itself but not from remote ones.
I'm using Addon-SDK now and my code is
And then
function injectTest(event) {
let domWindow = event.subject;
//This creates and object that is always visible but never accesible from page not loaded by the extension
foo = Cu.createObjectIn(domWindow.wrappedJSObject, {defineAs: "testSDK"});
//This exports my function fine but I can export it only into an existing object
//That's why I'm using "crypto" here
Cu.exportFunction(test.bind(this, domWindow),
domWindow.crypto.wrappedJSObject,
{ defineAs: "test" });
//This exports my function to my object but only on pages loaded by the extension
Cu.exportFunction(test.bind(this, domWindow),
foo,
{ defineAs: "test2" });
//Same here, cloned_var seems to be not accesible from remote webpage
var to_be_cloned = {"greet" : "hey"};
foo.cloned_var = Cu.cloneInto(to_be_cloned, foo);
}
exports.main = function(options, callbacks) {
if (!gInitialized &&
(options.loadReason == "startup" ||
options.loadReason == "install" ||
options.loadReason == "enable")) {
log("initializing - " + options.loadReason);
try {
events.on("content-document-global-created", injectTest);
} catch (error) {
log(error);
}
gInitialized = true;
}
};
I'm totally new to javascript and Firefox extensions so I have no idea how to make it work. What I'm doing wrong? Is there any better idea to access extension's objects?
Thank you in advance for help.
#edit 19.05.15
Tried using page-mod. It does work but not as well as I need.
main.js file
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
pageMod.PageMod({
include: "mywebsite",
contentScriptFile: [data.url("cscript.js")],
contentScript: 'window.alert("Page matches ruleset");'
});
cscript.js file (in data folder)
var contentScriptObject = {
"greeting" : "hello from add-on",
b: 1,
powitaj: function(){
return(this.greeting);
}, //when called from console returns "hello from add-on"
is_b: function(){
if(b){
return true;
}else{
return false;
}
}, //undefined
is_thisb: function(){
if(this.b){
return true;
}else{
return false;
}
}, //returns 1
func: function(){
console.log("ok")
}, //returns "ok"
is_func: function(){
func();
}, //undefined
is_thisfunc:function(){
this.func();
} //undefined
};
So from my website I can access inner variables (actually variables defined globally too and modify them as well), I can access inner functions (not outer - not included in the code) but my inner functions cannot call each other and I'd like to be able to do that.
To run chrome-privileged code in a e10s-content process you'll need framescripts
The SDK has some wrapper modules to simplify the communication and module loading between parent and child process
If you only need exportFunction/cloneInto/createObjectIn then using the page-mod module may be sufficient, if i recall correctly those helpers are made available in its context.

jQuery + Javascript - accessing object fields in anonymous function

I'm not into JavaScript OOP, so I've made an object with some fields which contains some functions to invoke.
var test = {
questions: [],
addQuestion: function(questionTitle, possibleAnwsers)
{
// not really important
},
appendQuestionToHTML: function(question)
{
// not really important
},
makeQuestionFieldsEditable: function($questionNode)
{
$questionNode.find(".questionTitle").first(function(){this.changeTextOnClick($(this));});
$questionNode.find(".questionChoice").each(function(){this.changeTextOnClick($(this));});
},
changeTextOnClick: function($spanElement)
{
// not really important
}
};
Following object in makeQuestionFieldsEditable() function looks for ".questionTitle"-class node and all of ".questionChoice"-class nodes invoke another function for them.
The problem is that using this in anonymous function references to itself, not function saved on field changeTextOnClick.
Javascript/JQuery wants to invoke this function on HTMLDivElement, which doesn't exists.
Is there any solution?
You can do the trick using a reference to your this variable :
makeQuestionFieldsEditable: function($questionNode)
{
var that = this;
$questionNode.find(".questionTitle").first(function(){that.changeTextOnClick($(this));});
$questionNode.find(".questionChoice").each(function(){that.changeTextOnClick($(this));});
},
I think all you need to do is change 'this' to 'test' (the variable you have assigned this object to).

Categories